gpt4 book ai didi

python - Tkinter - 如何停止在 Canvas 窗口上方滚动

转载 作者:行者123 更新时间:2023-12-04 16:39:37 26 4
gpt4 key购买 nike

我有一个可滚动的框架,鼠标滚轮绑定(bind)到滚动,但是当框架小于 Canvas 时,我可以在它上面滚动 - 如何让框架保持在 Canvas 的顶部?

这是代码的最小版本:

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()

最佳答案

您可以定义自己的 yview() 方法,该方法仅在 Canvas 的全部内容不可见时才进行滚动。为此,我使用了 self.canvas.yview(),如果所有 Canvas 内容都可见,它会返回 (0.0, 1.0)。然后我将自定义 yview() 方法用作滚动条命令和鼠标滚轮绑定(bind)。

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.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.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()

def yview(self, *args):
if self.canvas.yview() == (0.0, 1.0):
return
self.canvas.yview(*args)

if __name__ == "__main__":
root = tk.Tk()
gui = Gui(root)
root.mainloop()

关于python - Tkinter - 如何停止在 Canvas 窗口上方滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63629407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com