【问题标题】:Tkinter - Same event for multiple buttonsTkinter - 多个按钮的相同事件
【发布时间】:2016-05-29 23:56:57
【问题描述】:

使用 Tkinter,我有很多按钮。我希望每次按下任何按钮时都会触发相同的回调函数。我怎样才能知道按下了哪个按钮?

def call(p1):
    # Which Button was pressed?
    pass

for i in range (50):
    B1 = Button(master, text = '...', width = 2)
    B1.grid(row = i*20, column = 60)               
    B1.bind('<Button-1>',call)

    B2 = Button(master, text = '...', width = 2)
    B2.grid(row = i*20, column = 60)               
    B2.bind('<Button-1>',call)

【问题讨论】:

    标签: events tkinter


    【解决方案1】:

    使用列表来引用动态创建的按钮和 lambda 来存储对按钮对象索引的引用。您可以确定单击了哪个按钮。在下面的示例中,我在按钮对象上使用.cget("text") 来演示如何访问按钮小部件。

    import tkinter as tk
    
    root = tk.Tk()
    root.minsize(200, 200)
    
    btn_list = [] # List to hold the button objects
    
    def onClick(idx):
        print(idx) # Print the index value
        print(btn_list[idx].cget("text")) #Print the text for the selected button
    
    for i in range(10):
        # Lambda command to hold reference to the index matched with range value
        b = tk.Button(root, text = 'Button #%s' % i, command = lambda idx = i: onClick(idx))
        b.grid(row = i, column = 0)
    
        btn_list.append(b) # Append the button to a list
    
    root.mainloop()
    

    或者,您可以使用绑定,然后从生成的事件对象访问小部件。

    import tkinter as tk
    
    root = tk.Tk()
    root.minsize(200, 200)
    
    def onClick(event):
        btn = event.widget # event.widget is the widget that called the event
        print(btn.cget("text")) #Print the text for the selected button
    
    for i in range(10):
        b = tk.Button(root, text = 'Button #%s' % i)
        b.grid(row = i, column = 0)
        # Bind to left click which generates an event object
        b.bind("<Button-1>", onClick)
    
    root.mainloop()
    

    【讨论】:

      【解决方案2】:
      1. @Steven Summers 的第一个示例对我来说似乎是最清楚的,但我认为在没有列表的情况下这样做会更清楚。
      2. 按照我理解问题的方式,您不仅想知道点击了哪个按钮,而且希望每个按钮都能调用另一个未描述的函数(在下面的示例中为universal)。在这种情况下,您可以使用非常方便的 combine_funcs(参见:Have multiple commands when button is pressed)从一个小部件调用两个函数。

      这是我的代码。而不是一个列表,我只是有一个字符串,每次点击都会更改和打印。

      import tkinter as tk
      
      root = tk.Tk()
      root.minsize(200, 200)
      
      buttonVal = ''                             
      
      def combine_funcs(*funcs):
          def combined_func(*args, **kwargs):
              for f in funcs:
                  f(*args, **kwargs)
          return combined_func
      
      def universal():
          print 'Universal function is called'    
      
      def button_check(buttonName):
          buttonVal = buttonName
          print buttonVal   # Or whatever you want to do with the button info
      
      for i in range(10):
          B1 = tk.Button(root, text = 'Button #%s' % i, command = combine_funcs(universal, lambda buttonName = 'Button #%s' % i:button_check(buttonName)))
          B1.grid(row = i, column = 0)
      
      root.mainloop()
      

      【讨论】:

        【解决方案3】:

        使用lambda

        B1 = Button(master, text = '...', width = 2, command = lambda: call('B1') )
        

        等等……

        【讨论】:

          【解决方案4】:

          这可能不是最简单的解决方案,但它是我能想到的唯一解决方案。

          from Tkinter import *
          master = Tk()
          
          L = []
          
          def call(p1):
              for i in range(len(L)):
                  if str(L[i]) == str(p1.widget):
                      print 'Button' + str(i)
                      break  
          
          for i in range (50):
              exec("Button" + str(i) + " = Button(master, text = '...', width = 2)")
              exec("Button" + str(i) + ".grid(row = i*20, column = 60)")               
              exec("Button" + str(i) + ".bind('<Button-1>',call)")
          
              s = 'L.append(str(Button' + str(i) + '))'
              exec(s)
          

          【讨论】:

          • 你为什么使用exec?这没有任何意义。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-31
          • 2020-07-24
          • 2012-07-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多