2012-05-05 28 views
6

我想在Python中用Tkinter編寫一個簡單的用戶界面,我無法獲取網格中的小部件來調整大小。每當我調整主窗口大小時,入口和按鈕小部件根本不會調整。Tk網格將不會正確調整大小

這裏是我的代碼:

class Application(Frame): 
    def __init__(self, master=None): 
     Frame.__init__(self, master, padding=(3,3,12,12)) 
     self.grid(sticky=N+W+E+S) 
     self.createWidgets() 

    def createWidgets(self): 
     self.dataFileName = StringVar() 
     self.fileEntry = Entry(self, textvariable=self.dataFileName) 
     self.fileEntry.grid(row=0, column=0, columnspan=3, sticky=N+S+E+W) 
     self.loadFileButton = Button(self, text="Load Data", command=self.loadDataClicked) 
     self.loadFileButton.grid(row=0, column=3, sticky=N+S+E+W) 

     self.columnconfigure(0, weight=1) 
     self.columnconfigure(1, weight=1) 
     self.columnconfigure(2, weight=1) 

app = Application() 
app.master.title("Sample Application") 
app.mainloop() 

回答

14

添加一個根窗口和列配置它,以便您的框架小部件也展開。這就是問題所在,如果你沒有指定一個根窗口,並且這個框架本身就是不能正確擴展的,你就會得到一個隱含的根窗口。

root = Tk() 
root.columnconfigure(0, weight=1) 
app = Application(root) 
+2

增加了rowconfigure以允許垂直擴展 –

0

我用包這一點。在大多數情況下,這就足夠了。 但是不要混合兩者!

class Application(Frame): 
    def __init__(self, master=None): 
     Frame.__init__(self, master) 
     self.pack(fill = X, expand =True) 
     self.createWidgets() 

    def createWidgets(self): 
     self.dataFileName = StringVar() 
     self.fileEntry = Entry(self, textvariable=self.dataFileName) 
     self.fileEntry.pack(fill = X, expand = True) 
     self.loadFileButton = Button(self, text="Load Data",) 
     self.loadFileButton.pack(fill=X, expand = True) 
+0

我會考慮使用包而不是網格,但從我已閱讀的網格中也應該調整窗口小部件的大小。 – mjn12

+0

我沒有長時間使用電網,所以我不知道。祝你好運! – User

0

一個工作示例。請注意,您必須爲每個列和所使用的行顯式設置配置,但下面的按鈕的列大小是大於顯示列數的數字。

## row and column expand 
top=tk.Tk() 
top.rowconfigure(0, weight=1) 
for col in range(5): 
    top.columnconfigure(col, weight=1) 
    tk.Label(top, text=str(col)).grid(row=0, column=col, sticky="nsew") 

## only expands the columns from columnconfigure from above 
top.rowconfigure(1, weight=1) 
tk.Button(top, text="button").grid(row=1, column=0, columnspan=10, sticky="nsew") 
top.mainloop() 
相關問題