2014-02-06 172 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