简体   繁体   English

Python 2.7 Tkinter:如何单击并释放两个小部件并同时获得两个小部件的响应?

[英]Python 2.7 Tkinter: how do I click & release on two widgets and get responses from both?

I hope you can help me with a problem I have in python 2.7. 我希望您能为我解决python 2.7中的问题提供帮助。 I couldn't find a solution online, but I'm honestly unsure what keywords to search for, so I'm sorry if this is redundant. 我无法在线找到解决方案,但是老实说,我不确定要搜索哪些关键字,如果这很多余,我感到抱歉。

The code below is an example of my problem. 下面的代码是我的问题的一个示例。

import Tkinter as tk

root = tk.Tk()

#Widgets.
btn1 = tk.Label(root, text="btn1", bg="gray80")
btn2 = tk.Label(root, text="btn2", bg="gray80")
btn1.pack(side=tk.TOP, fill=tk.X)
btn2.pack(side=tk.TOP, fill=tk.X)

#Widget events.
def onClick1(event):
    print "Clicked button 1."
def onRelease1(event):
    print "Released button 1."
def onClick2(event):
    print "Clicked button 2."
def onRelease2(event):
    print "Released button 2."

#Bindings.
btn1.bind("<Button-1>", onClick1, add="+")
btn1.bind("<ButtonRelease-1>", onRelease1, add="+")
btn2.bind("<Button-1>", onClick2, add="+")
btn2.bind("<ButtonRelease-1>", onRelease2, add="+")

root.mainloop()

Whenever I click one button (technically a label) and hold it, the onClick event for it fires, but if I drag the mouse over to the other and release it, I get the same onRelease as the one I clicked, and not the one for the label I have my mouse over currently. 每当我单击一个按钮(严格来说是一个标签)并按住它时,都会触发它的onClick事件,但是如果将鼠标拖到另一个按钮上并释放它,我会获得与单击的按钮相同的onRelease,而不是一个对于标签,我目前将鼠标悬停在上方。 This has held me back some time now, and I'd hate to scrap the whole feature in my program I need this for, so any help would be greatly appreciated. 这使我退缩了一段时间,而且我不想在我需要此功能的程序中取消整个功能,因此,我们将不胜感激。

The release event always fires on the same widget that got the press event. 释放事件总是在与按下事件相同的窗口小部件上触发。 Within your handler you can ask tkinter what widget is under the cursor. 在您的处理程序中,您可以询问tkinter光标下的小部件。

Example: 例:

import Tkinter as tk

root = tk.Tk()

btn1 = tk.Label(root, text="btn1", bg="gray80")
btn2 = tk.Label(root, text="btn2", bg="gray80")
btn1.pack(side=tk.TOP, fill=tk.X)
btn2.pack(side=tk.TOP, fill=tk.X)

def onRelease(event):
    x,y = event.widget.winfo_pointerxy()
    widget = event.widget.winfo_containing(x, y)
    print("widget:", widget.cget("text"))

btn1.bind("<ButtonRelease-1>", onRelease)
btn2.bind("<ButtonRelease-1>", onRelease)

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM