【问题标题】:How to know whether a button is clicked in tkinter?如何知道在 tkinter 中是否单击了按钮?
【发布时间】:2020-12-07 06:04:09
【问题描述】:

如果单击按钮,我想执行一项任务。我该怎么做呢?我可以使用两个单独的函数来执行任务,但我在'hey' 中的'if' 块之后有一大段代码,我不想再次输入整个内容。我的代码是:

from tkinter import *

root = Tk()

def hey():
    if bt1 is clicked:
        #do something
    if bt2 is clicked:
        #do something

    #some piece of code

bt1 = Button(root, text = 'yes', command = hey)
bt2 = Button(root, text = 'no', command = hey)

bt1.pack()
bt2.pack()

【问题讨论】:

    标签: python tkinter button click


    【解决方案1】:

    根据您分享的内容,您可以使用参数在按钮中传递标志,例如

    bt1 = Button(root, text = 'yes', command =lambda: hey(True))
    bt2 = Button(root, text = 'no', command =lambda: hey(False))
    

    而在代码中,你可以做到,

    def hey(which): # `which` decides which statement to be followed
        if which:
            #do something
        else:
            #do something
    

    【讨论】:

      【解决方案2】:
      from tkinter import *
      
      root = Tk()
      
      def func():
           #common code for both buttons
      
      def hey(arg):
          if arg == 1:
              print("button 1 used")
              func() #mention arguments if required
          elif arg == 2:
              print("button 2 used")
              func() 
      
      
      bt1 = Button(root, text = 'yes', command=lambda: hey(1))
      bt2 = Button(root, text = 'no', command=lambda: hey(2))
                 # you can add more buttons to do the same function,use hey(n)
      bt1.pack()
      bt2.pack()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-23
        • 2021-05-17
        • 2017-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多