Tkinter - 如何停止在画布窗口上方滚动

我有一个可滚动框架,鼠标滚轮绑定到滚动,但是当框架小于画布时,我可以在其上方滚动 - 如何将框架保持在画布顶部?


这是代码的最小版本:


import tkinter as tk


class Gui:

    def __init__(self, master):

        self.root = master

        self.canvas = tk.Canvas(self.root)

        self.frame = tk.Frame(self.canvas,bg='white')

        self.scroll = tk.Scrollbar(self.canvas,orient='vertical', command=self.canvas.yview)

        self.canvas.configure(yscrollcommand=self.scroll.set)


        self.scroll.pack(side='right', fill='y')

        self.canvas.place(relheight=1, relwidth=0.85, relx=0.15)

        self.canvas_frame = self.canvas.create_window((0,0), window=self.frame, anchor='nw')


        self.frame.bind('<Configure>', self.onFrameConfigure)

        self.canvas.bind_all('<MouseWheel>', lambda event: self.canvas.yview_scroll(int(-1*(event.delta/120)), 'units'))

        self.addToFrame()

    def onFrameConfigure(self, event):

        self.canvas.configure(scrollregion=self.canvas.bbox('all'))


    def addToFrame(self):

        self.label = tk.Label(self.frame,text='Label')

        self.label.pack()

        

if __name__ == "__main__":

    root = tk.Tk()

    gui = Gui(root)

    root.mainloop()


开满天机
浏览 168回答 1
1回答

阿波罗的战车

您可以定义自己的yview()方法,仅当画布的全部内容不可见时才进行滚动。为此,我使用了,如果所有画布内容都可见,self.canvas.yview()则返回。(0.0, 1.0)然后我使用自定义yview()方法作为滚动条命令和鼠标滚轮绑定。import tkinter as tkclass Gui:&nbsp; &nbsp; def __init__(self, master):&nbsp; &nbsp; &nbsp; &nbsp; self.root = master&nbsp; &nbsp; &nbsp; &nbsp; self.canvas = tk.Canvas(self.root)&nbsp; &nbsp; &nbsp; &nbsp; self.frame = tk.Frame(self.canvas,bg='white')&nbsp; &nbsp; &nbsp; &nbsp; self.scroll = tk.Scrollbar(self.canvas,orient='vertical', command=self.yview)&nbsp; &nbsp; &nbsp; &nbsp; self.canvas.configure(yscrollcommand=self.scroll.set)&nbsp; &nbsp; &nbsp; &nbsp; self.scroll.pack(side='right', fill='y')&nbsp; &nbsp; &nbsp; &nbsp; self.canvas.place(relheight=1, relwidth=0.85, relx=0.15)&nbsp; &nbsp; &nbsp; &nbsp; self.canvas_frame = self.canvas.create_window((0,0), window=self.frame, anchor='nw')&nbsp; &nbsp; &nbsp; &nbsp; self.frame.bind('<Configure>', self.onFrameConfigure)&nbsp; &nbsp; &nbsp; &nbsp; self.canvas.bind_all('<MouseWheel>', lambda event: self.yview('scroll', int(-1*(event.delta/120)), 'units'))&nbsp; &nbsp; &nbsp; &nbsp; self.addToFrame()&nbsp; &nbsp; def onFrameConfigure(self, event):&nbsp; &nbsp; &nbsp; &nbsp; self.canvas.configure(scrollregion=self.canvas.bbox('all'))&nbsp; &nbsp; def addToFrame(self):&nbsp; &nbsp; &nbsp; &nbsp; self.label = tk.Label(self.frame,text='Label')&nbsp; &nbsp; &nbsp; &nbsp; self.label.pack()&nbsp; &nbsp; def yview(self, *args):&nbsp; &nbsp; &nbsp; &nbsp; if self.canvas.yview() == (0.0, 1.0):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; self.canvas.yview(*args)if __name__ == "__main__":&nbsp; &nbsp; root = tk.Tk()&nbsp; &nbsp; gui = Gui(root)&nbsp; &nbsp; root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python