2014-02-06 132 views
0

我想做一個Tkinter窗口類,它包含一個基於tkinter Toplevel類的滾動條的畫布。當我運行我的代碼時,我沒有收到任何錯誤,但窗口中的滾動條被禁用。在程序運行後手動拉伸時,具有信息的框架或畫布不會與窗口拉伸。這裏是bug的代碼:Tkinter,畫布無法滾動

class new_window(Toplevel): 

    def __init__(self,master): 
     Toplevel.__init__(self,master) 


     self.grid_rowconfigure(0, weight=1) 
     self.grid_columnconfigure(0, weight=1) 

     s = Scrollbar(self, orient = VERTICAL) 
     s.grid(row = 0, column = 1, sticky = NS) 
     self.can = Canvas(self, yscrollcommand=s.set) 
     self.can.grid(row = 0, column = 0, sticky = N+S+E+W) 
     self.win = Frame(self.can) 
     self.can.create_window(0,0, window = self.win, anchor = NW) 
     s.config(command = self.can.yview) 

     size = (self.win.winfo_reqwidth(), self.win.winfo_reqheight()) 
     self.can.config(scrollregion="0 0 %s %s" % size) 

     self.win.update_idletasks() 
     self.ca.configure(scrollregion = (1,1,win.winfo_width(),win.winfo_height())) 


    def create(self): 
     for i in range (100): 
      i = Label(self.win, text = str(i)) 
      i.grid() 


root = Tk() 

win = new_window(root) 
win.create() 
root.mainloop() 

這是工作的罰款之前,我決定實現類:

from Tkinter import * 

root = Tk() 

window = Toplevel() 
window.grid_rowconfigure(0, weight=1) 
window.grid_columnconfigure(0, weight=1) 

s = Scrollbar(window, orient = VERTICAL) 
s.grid(row = 6, column = 1, sticky = NS) 
can = Canvas(window, width = 1600, height = 700, yscrollcommand=s.set) 
can.grid(row = 6, column = 0, sticky = NSEW) 
win = Frame(can) 
can.create_window(0,0, window = win, anchor = NW) 
s.config(command = can.yview) 

for i in range(100): 
    lbl = Label(win, text = str(i)) 
    lbl.grid() 

win.update_idletasks() 
can.configure(scrollregion = (1,1,win.winfo_width(),win.winfo_height())) 

root.mainloop() 

林不知道我哪裏做錯了轉變,任何幫助將不勝感激。

回答

1

我認爲這個問題是從這裏來的:

self.win.update_idletasks() 
self.ca.configure(scrollregion = (1,1,win.winfo_width(),win.winfo_height())) 

這是初始化函數,當它的創建函數被調用後,應更新中。仍然可能有更有效的方法來構建這個,但這應該在此期間工作:

from Tkinter import * 

class new_window(Toplevel): 

    def __init__(self,master): 
     Toplevel.__init__(self,master) 

     self.grid_rowconfigure(0, weight=1) 
     self.grid_columnconfigure(0, weight=1) 

     s = Scrollbar(self, orient = VERTICAL) 
     s.grid(row = 0, column = 1, sticky = NS) 
     self.can = Canvas(self, yscrollcommand=s.set) 
     self.can.grid(row = 0, column = 0, sticky = N+S+E+W) 
     self.win = Frame(self.can) 
     self.can.create_window(0,0, window = self.win, anchor = NW) 
     s.config(command = self.can.yview) 

     size = (self.win.winfo_reqwidth(), self.win.winfo_reqheight()) 
     self.can.config(scrollregion="0 0 %s %s" % size) 

    def create(self): 
     for i in range (100): 
      i = Label(self.win, text = str(i)) 
      i.grid() 
     self.win.update_idletasks() 
     self.can.configure(scrollregion = (1,1,self.win.winfo_width(),self.win.winfo_height())) 

root = Tk() 

win = new_window(root) 
win.create() 
root.mainloop() 
+0

非常感謝您的快速回復 – Parzzival