gpt4 book ai didi

python /Tkinter : The order of mouse events different in scrollbar widget

转载 作者:行者123 更新时间:2023-12-04 15:23:47 25 4
gpt4 key购买 nike

我正在检查通过以下代码拖动 slider 时的鼠标事件。对于不同的小部件,我得到了不同的鼠标事件顺序。

对于Canvas来说,看起来很正常

<ButtonPress-1>
<B1-Motion>
...
<B1-Motion>
<ButtonRelease-1>

对于滚动条,它看起来顺序不对

<B1-Motion>
...
<B1-Motion>
<ButtonRelease-1>
<ButtonPress-1>
from tkinter import *

def start(event):
print('<ButtonPress-1>')

def stop(event):
print('<ButtonRelease-1>')

def motion(event):
print('<B1-Motion>')

root = Tk()

canv = Canvas(width=600, height=400, scrollregion=(0, 0, 1200, 800))
canv.grid(row=0, column=0)
scrollY = Scrollbar(orient=VERTICAL, command=canv.yview)
scrollY.grid(row=0, column=1, sticky=N+S)
scrollX = Scrollbar(orient=HORIZONTAL, command=canv.xview)
scrollX.grid(row=1, column=0, sticky=E+W)
canv['xscrollcommand'] = scrollX.set
canv['yscrollcommand'] = scrollY.set

root.bind("<ButtonPress-1>", start)
root.bind("<ButtonRelease-1>", stop)
root.bind("<B1-Motion>", motion)

root.mainloop()

我的问题是为什么滚动条小部件的鼠标事件顺序是错误的? slider 拖动和箭头单击的问题相同。可以设置成正常的时序吗?或者我可以在为 slider 拖动或箭头单击完成滚动条操作后绕过事件吗?

环境:

  1. WIN10
  2. python 3.8.3
  3. Tkinter TkVersion 8.6

最佳答案

我实际上不确定为什么会这样,但是使用 ttk 就可以了。我假设在后台有类似 wait_var() 的东西,并且变量在按钮被释放后才发生变化。

from tkinter import *
from tkinter import ttk

def start(event):
print('<ButtonPress-1>')

def stop(event):
print('<ButtonRelease-1>')

def motion(event):
print('<B1-Motion>')

root = Tk()

canv = Canvas(width=600, height=400, scrollregion=(0, 0, 1200, 800))
canv.grid(row=0, column=0)
scrollY = ttk.Scrollbar(orient=VERTICAL, command=canv.yview)
scrollY.grid(row=0, column=1, sticky=N+S)
scrollX = ttk.Scrollbar(orient=HORIZONTAL, command=canv.xview)
scrollX.grid(row=1, column=0, sticky=E+W)
canv['xscrollcommand'] = scrollX.set
canv['yscrollcommand'] = scrollY.set

root.bind("<ButtonPress-1>", start)
root.bind("<ButtonRelease-1>", stop)
root.bind("<B1-Motion>", motion)

root.mainloop()

关于 python /Tkinter : The order of mouse events different in scrollbar widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62723442/

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