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

标签 python events tkinter scrollbar

我正在检查通过以下代码拖动 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/

相关文章:

java - 如何将 "subscribe"发送给 Java 工厂创建的对象上的事件?

python - 错误说明 - 'statInter' 对象没有属性 'tk'

python - Windows下如何改变Tkinter菜单的颜色?

Python 使用 matplotlib 在 x 轴上显示特定值

python 请求抓取帖子并从下拉菜单中填写表单

python 使用 pool.map_async 时没有输出

delphi - 知道 Onclick 事件被触发

python - 如何从Python脚本在默认编辑器中打开python文件

jquery - 如何使用 on() 和 off() 将事件附加到 jQuery 移动页面?

Python Tkinter 无法在 .py 文件中工作