【问题标题】:Change command Method for Tkinter Button in Python在 Python 中更改 Tkinter 按钮的命令方法
【发布时间】:2010-09-09 06:14:36
【问题描述】:

我创建了一个新的 Button 对象,但在创建时没有指定 command 选项。 Tkinter 有没有办法在创建对象后更改命令(onclick)功能?

【问题讨论】:

    标签: python user-interface tkinter


    【解决方案1】:

    尽管Eli Courtwright's 程序可以正常工作¹,但您真正想要的只是一种在实例化后重新配置您在实例化时可以设置的任何属性的方法²。你如何做到这一点是通过 configure() 方法。

    from Tkinter import Tk, Button
    
    def goodbye_world():
        print "Goodbye World!\nWait, I changed my mind!"
        button.configure(text = "Hello World!", command=hello_world)
    
    def hello_world():
        print "Hello World!\nWait, I changed my mind!"
        button.configure(text = "Goodbye World!", command=goodbye_world)
    
    root = Tk()
    button = Button(root, text="Hello World!", command=hello_world)
    button.pack()
    
    root.mainloop()
    

    ¹ 如果您只使用鼠标,则“很好”;如果您关心制表符并在按钮上使用 [Space] 或 [Enter],那么您也必须实现(复制现有代码)按键事件。通过.configure 设置command 选项要容易得多。

    ²实例化后唯一不能改变的属性是name

    【讨论】:

      【解决方案2】:

      当然;只需使用bind 方法来指定按钮创建后的回调。我刚刚编写并测试了下面的示例。你可以在http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm找到一个很好的教程。

      from Tkinter import Tk, Button
      
      root = Tk()
      button = Button(root, text="Click Me!")
      button.pack()
      
      def callback(event):
          print "Hello World!"
      
      button.bind("<Button-1>", callback)
      root.mainloop()
      

      【讨论】:

      • 命令配置选项通常用于按钮按下。回调函数不需要事件参数。
      • 使用绑定并不是一个特别好的解决方案 IMO。这正是 -command 选项的用途。另外,通过在绑定中执行此操作,您将失去通过键盘遍历调用回调的能力,除非您还添加键绑定。它很快就会变得非常混乱,所以坚持使用 -command。
      猜你喜欢
      • 2012-10-06
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多