2014-09-19 30 views
3

我剛剛開始使用Python的Tkinter/ttk,我在使用網格佈局時遇到問題,無法調整我的小部件的大小。這是我的代碼的一個子集,展示與完整代碼相同的問題(我意識到這個子集非常簡單,我可能會更好使用pack而不是grid,但我認爲這將有助於切入主要問題有一次我明白,我可以修復它無處不在我的全程序中出現):Python:tk入門,窗口小部件沒有在網格上調整大小?

import Tkinter as tk 
import ttk 

class App(tk.Frame): 
    def __init__(self, master): 
     tk.Frame.__init__(self, master) 

     # Create my widgets 
     self.tree = ttk.Treeview(self) 
     ysb = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview) 
     xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tree.xview) 
     self.tree.configure(yscroll=ysb.set, xscroll=xsb.set) 
     self.tree.heading('#0', text='Path', anchor='w') 

     # Populate the treeview (just a single root node for this simple example) 
     root_node = self.tree.insert('', 'end', text='Test', open=True) 

     # Lay it out on a grid so that it'll fill the width of the containing window. 
     self.tree.grid(row=0, column=0, sticky='nsew') 
     self.tree.columnconfigure(0, weight=1) 
     ysb.grid(row=0, column=1, sticky='nse') 
     xsb.grid(row=1, column=0, sticky='sew') 
     self.grid() 
     master.columnconfigure(0, weight=1) 
     self.columnconfigure(0, weight=1) 

app = App(tk.Tk()) 
app.mainloop() 

我想讓它讓我的樹視圖填補它在窗口的整個寬度,而是樹視圖正好在窗戶中間居中。

+0

我猜你的意思是在第一行輸入「Tkinter as tk」? – Kevin 2014-09-19 18:38:08

+0

@凱文 - 對。有趣的事情:我手動編寫了前3行代碼,之後纔想到「我最好只是複製並粘貼以避免犯錯誤」,然後複製並粘貼剩下的部分。 – ArtOfWarfare 2014-09-19 19:45:23

回答

2

嘗試在self.grid處指定sticky參數。沒有它,框架不會調整窗口的大小。你還需要rowconfigure主人和自己,就像你有columnconfigure他們一樣。

#rest of code goes here... 
    xsb.grid(row=1, column=0, sticky='sew') 
    self.grid(sticky="nesw") 
    master.columnconfigure(0, weight=1) 
    master.rowconfigure(0,weight=1) 
    self.columnconfigure(0, weight=1) 
    self.rowconfigure(0, weight=1) 

另一方面,不是網格框架,pack並指定它填充它佔用的空間。由於Frame是Tk中唯一的小部件,因此無論您是pack還是grid都無關緊要。

#rest of code goes here... 
    xsb.grid(row=1, column=0, sticky='sew') 
    self.pack(fill=tk.BOTH, expand=1) 
    self.columnconfigure(0, weight=1) 
    self.rowconfigure(0, weight=1) 
+0

感謝Kevin!你是對的,我只需要改變它,讓它開始調整窗口的大小就可以在'sticky ='nsew''中添加'self.grid()'的參數。正如我在問題中所說的那樣,這只是我的代碼的一個最小子集,它演示了我所遇到的問題 - 我的實際程序的佈局更多地使'grid()'更適合'pack()'。但修復這條線可以修復我的完整程序中的所有縮放比例。再次感謝! – ArtOfWarfare 2014-09-19 19:49:10

相關問題