2016-09-06 57 views
0

我正在使用放置在畫布上的多個小部件來顯示通過多個任務的進度。爲了做到這一點,我把它們放在一個框架中的畫布上的網格中。幾乎所有的工作,但我需要滾動條默認到窗口的底部(框架)。我試圖使用vsb.set強制滾動條到一個新的位置,但它沒有效果。如果我使用事件處理程序來移動滾動條,我將失去對其移動的控制。我是一個新手,並會讚賞一些輸入。見下面的代碼。在畫布上自動滾動多個小部件

from tkinter import * 
import tkinter as tk 

class example(Frame): 
    def __init__(self, root): 
     Frame.__init__(self, root) 
     self.initUI() 

    def initUI(self): 
     self.canvas = Canvas(root, borderwidth=0, background="#ffffff", height=300, width=700) 
     self.frame = Frame(self.canvas, background="#ffffff") 
     self.vsb = Scrollbar(root, orient="vertical", command=self.canvas.yview) 
     self.canvas.configure(yscrollcommand=self.vsb.set) 
     self.vsb.pack(side="right", fill="y") 
     self.canvas.pack(side="left", fill="both", expand=True) 
     self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") 
     self.frame.bind("<Configure>", self.onFrameConfigure) 
     root.title("Issue with Scrolling through Widgets") 
     self.populate()  

    def onFrameConfigure(self, event): 
     ###Reset the scroll region to encompass the inner frame 
     self.canvas.configure(scrollregion=self.canvas.bbox("all")) 
     self.canvas.bind_all("<MouseWheel>", self._on_mousewheel) 

    def _on_mousewheel(self, event): 
     self.canvas.yview_scroll(-1*int(event.delta/120),"units") 

    def populate(self): 
     ###Put in some fake data### 
     for row in range(20):       
      Txt = Text(self.frame, bg="white", borderwidth=1, height=1, width=40) 
      Txt.grid(row = row, column = 0, rowspan = 1, columnspan = 1, sticky = W+E+N+S) 
      line = "this is the first column for row %s" %row 
      Txt.insert(END, str(line)) 
      Txt = Text(self.frame, bg="white", borderwidth=1, height=1, width=40) 
      Txt.grid(row = row, column = 1, rowspan = 1, columnspan = 1, sticky = W+E+N+S) 
      line = "this is the second column for row %s" %row 
      Txt.insert(END, str(line)) 

if __name__ == "__main__": 
    root=Tk() 
    example(root).pack(side="top", fill="both", expand=True) 
    root.mainloop() 
+0

「默認爲窗口底部」,你是說你想讓內容滾動到底部,還是你的意思是你想讓實際的滾動條處於不同的物理位置? –

+0

我希望它默認顯示上次發送到窗口的內容。 –

回答

0

是的,我想讓滾動條向下移動,因爲新數據放在網格上。我發現了一個可行的解決方案,但我不確定它是否正確。我將onFrameConfigure函數更改爲以下內容。

def onFrameConfigure(self, event): # Reset the scroll region to encompass the inner frame 
    global insertFlag 
    self.canvas.configure(scrollregion=self.canvas.bbox("all")) 
    self.canvas.bind_all("<MouseWheel>", self._on_mousewheel) 
    if insertFlag == 1: 
     self.canvas.yview_scroll(20, "units") 
     insertFlag = 0 

然後添加到底部填充if語句來設置全局變量,如下所示。

def populate(self): 
    global insertFlag 
    for row in range(20): 
     Txt = Text(self.frame, bg="white", borderwidth=1, height=1, width=40) 
     Txt.grid(row = row, column = 0, rowspan = 1, columnspan = 1, sticky = W+E+N+S) 
     line = "this is the second column for row %s" %row 
     Txt.insert(END, str(line)) 
     Txt.see(END) 
    insertFlag = 1 

您認爲什麼,您的意見是讚賞。