【发布时间】:2011-06-27 15:35:39
【问题描述】:
我认为这是一个很常见的问题,但我找不到答案。
我正在尝试制作一个根据鼠标位置滚动的窗口:如果鼠标靠近屏幕顶部,它会滚动到顶部,如果它靠近右边框,它会向右滚动等等。代码如下:
from tkinter import *
from tkinter import ttk
root = Tk()
h = ttk.Scrollbar(root, orient = HORIZONTAL)
v = ttk.Scrollbar(root, orient = VERTICAL)
canvas = Canvas(root, scrollregion = (0, 0, 2000, 2000), width = 600, height = 600, yscrollcommand = v.set, xscrollcommand = h.set)
h['command'] = canvas.xview
v['command'] = canvas.yview
ttk.Sizegrip(root).grid(column=1, row=1, sticky=(S,E))
canvas.grid(column = 0, row = 0, sticky = (N,W,E,S))
h.grid(column = 0, row = 1, sticky = (W,E))
v.grid(column = 1, row = 0, sticky = (N,S))
root.grid_columnconfigure(0, weight = 1)
root.grid_rowconfigure(0, weight = 1)
canvas.create_rectangle((0, 0, 50, 50), fill = 'black')
canvas.create_rectangle((500, 500, 550, 550), fill = 'black')
canvas.create_rectangle((1500, 1500, 1550, 1550), fill = 'black')
canvas.create_rectangle((1000, 1000, 1050, 1050), fill = 'black')
def xy_motion(event):
x, y = event.x, event.y
if x < 30:
delta = -1
canvas.xview('scroll', delta, 'units')
if x > (600 - 30):
delta = 1
canvas.xview('scroll', delta, 'units')
if y < 30:
delta = -1
canvas.yview('scroll', delta, 'units')
if y > (600 - 30):
delta = 1
canvas.yview('scroll', delta, 'units')
canvas.bind('<Motion>', xy_motion)
root.mainloop()
问题是滚动运动在运动功能中,只有在鼠标移动时才有效(如果你停止移动鼠标,滚动也会停止)。我想让它成为一种方式,即使鼠标没有移动(但仍在“滚动区域”中),窗口也会继续滚动直到它到达末尾。
我认为显而易见的方法是将 if 语句(例如从第 30 行)更改为 while 语句,如下所示:
while x < 30:
但是当鼠标到达这个位置时,程序会冻结(我认为是等待 while 循环完成)。
有什么建议吗?
提前致谢。
更新
这是带有(或可能的)答案之一的工作代码。我不知道用答案更新问题本身是否正确,但我认为它对其他人有用。
x, y = 0, 0
def scroll():
global x, y
if x < 30:
delta = - 1
canvas.xview('scroll', delta, 'units')
elif x > (ws - 30):
delta = 1
canvas.xview('scroll', delta, 'units')
elif y < 30:
delta = -1
canvas.yview('scroll', delta, 'units')
elif y > (ws - 30):
delta = 1
canvas.yview('scroll', delta, 'units')
canvas.after(100, scroll)
def xy_motion(event):
global x, y
x, y = event.x, event.y
scroll()
canvas.bind('<Motion>', xy_motion)
【问题讨论】:
-
我不是 Tkinter 专家,但 this 可能会有所帮助
-
我觉得这很有帮助,除了变量
ws没有定义。根据上下文,我假设它是坐标
标签: python scroll mouse tkinter