【问题标题】:Stop Python 3 button click from passing through to form停止 Python 3 按钮单击从传递到表单
【发布时间】:2016-11-25 06:48:21
【问题描述】:

我编写了一个测试平台来了解按钮、表单和菜单绑定。创建一个框架并在其上放置一个按钮并创建一个菜单。绑定(绑定?)在单独的例程中单击按钮、菜单和表单。

(Windows 10 和 Ubuntu/Pi3)单击表单时,一切正常。单击按钮时,按钮例程运行,然后表单例程也运行。真的不想要这个。肯定没想到吧!我输入了一个全局布尔值来检测和停止,但这似乎很愚蠢。

如何限制表单在没有“愚蠢代码”的情况下也回答按钮单击。我无法想象为什么绑定无论如何都会传递给表单。我在这里错过了什么?

#!/usr/bin/python3

from tkinter import *

def ButtonClickedOnce(event=None):
  global ButtonJustPressed
  #Have to nullify the event somehow so the form does not get it, too.
  ButtonJustPressed = True  # Comment this to see the problem.
  print("Button Single Clicked - Primary Button")
pass

def FormClickedOnce(event=None):
  global ButtonJustPressed
  if ButtonJustPressed: ButtonJustPressed = False
  else: print("Form Single Clicked - Primary Button") 
pass

def MasterStart(event=None):
  print("Let's Go")
pass

def PgmExit(event=None):                           
  print("Primary Double Click on Button or F3, Stopping.") 
  root.destroy() 
pass

ButtonJustPressed = False

root = Tk()
root.wm_title('Bind Test')

menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
FM_Start = filemenu.add_command(label="Let's Go", accelerator = "F5",
                                command = lambda: MasterStart())  # Start 'er up.
FM_Exit  = filemenu.add_command(label="Let's Stop", accelerator = "F3",
                                command = lambda: PgmExit())  # Exit now.

menubar.add_cascade(label='File', menu=filemenu)
root.config(menu=menubar)

frame = Frame(root)
frame.pack()

MyButton = Button(frame, text='Mouse Clicks')
MyButton.pack()

#Mouse button bindings
MyButton.bind('<Button-1>', ButtonClickedOnce)
MyButton.bind('<Double-1>', PgmExit) 
root.bind('<Button-1>', FormClickedOnce)

#Key bindings
root.bind('<F3>',PgmExit)
root.bind('<F5>',MasterStart)

root.geometry('%dx%d+%d+%d' % (200, 200, 0, 0))
root.mainloop()

【问题讨论】:

    标签: python python-3.x button tkinter bind


    【解决方案1】:

    简答

    当您将事件绑定到根窗口时,该窗口中的每个小部件都会对该事件作出反应。这是理所当然的,否则就不可能在窗口中的任何地方进行绑定。

    解决你的问题的简单方法是ButtonClickedOnce需要返回字符串“break”,这样会阻止点击被绑定到根窗口处理。

    长答案

    当您绑定到一个小部件时,您实际上并没有绑定到该小部件。相反,您将绑定与 bind 标记 相关联。默认情况下,每个小部件都有一个与小部件同名的绑定标签。您可以使用bindtags 方法获取或设置小部件的绑定标签列表(例如:MyButton.bindtags())。

    当事件触发时,tkinter 将处理小部件的绑定标签列表,并为与每个绑定标签关联的任何事件调用回调,直到其中一个函数返回“break”或没有更多的绑定标签。

    当您创建一个小部件时,它最初会获得四个绑定标签 - 一个用于小部件,一个用于小部件类(不是 python 类,而是一个内部类),一个用于小部件所在的顶层窗口,以及一个名为“全部”。这些绑定标签是有序的,从最具体的(实际的小部件)到最不具体的(“全部”)。

    当一个事件被处理时,这些绑定标签被依次遍历。例如,如果您单击一个按钮并且该按钮具有绑定,则将调用绑定的函数。如果类上有绑定(大多数小部件都提供默认行为),则该绑定将触发。如果窗口上有绑定,则该绑定将触发。最后,如果“all”上有一个绑定,该绑定将触发。

    在这条链上的任何一点,如果绑定函数返回字符串“break”,则链将被打破,不再处理绑定标签。

    有关如何处理事件的稍长描述,请参阅此答案:https://stackoverflow.com/a/11542200/7432

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 2020-04-11
      • 2012-12-06
      • 2015-04-25
      • 1970-01-01
      • 2016-12-25
      • 2014-01-30
      • 1970-01-01
      • 2013-11-07
      相关资源
      最近更新 更多