代码之家  ›  专栏  ›  技术社区  ›  FranticFronk

Tkinter单选按钮在已选择时执行命令

  •  1
  • FranticFronk  · 技术社区  · 6 月前

    在Tkinter应用程序中,我想执行 on_choice 选择时的功能 Radiobutton 通过使用 command=on_choice 。在单选按钮已被选择的情况下按下时,不应再次执行该功能。从另一个单选按钮切换后,只应执行一次,因此用户无法通过按下同一单选按钮重复执行功能。是否有方法防止在以下情况下执行命令 单选按钮 是否已选定?

    代码:

    import tkinter as tk
    
    def on_choice():
        print('Function executed')
    
    root = tk.Tk()
    root.geometry('300x150')
    
    radiobutton_variable = tk.StringVar()
    radiobutton_variable.set(1)
    button_1 = tk.Radiobutton(root, text='Button 1', variable=radiobutton_variable, value=1, command=on_choice)
    button_2 = tk.Radiobutton(root, text='Button 2', variable=radiobutton_variable, value=2, command=on_choice)
    
    button_1.pack()
    button_2.pack()
    
    root.mainloop()
    
    1 回复  |  直到 6 月前
        1
  •  0
  •   JRiggles    6 月前

    一个简单的解决方案是使用变量来跟踪 Radiobutton 最后按下(我称之为 prev_btn 这里)。

    这个 command 函数可以检查此值,并且只有当它与上次调用函数时相比发生更改时才能执行。之后,该函数存储更新的按钮值。

    import tkinter as tk
    
    
    def on_choice():
        # set prev_btn  as a global so this function can modify its value
        global prev_btn
        # only trigger the useful stuff if the button is different from last time
        if radiobutton_variable.get() != prev_btn:  # if button changed...
            print('Function executed')
            # store the value of the most recently pressed button
            prev_btn = radiobutton_variable.get()
    
    
    root = tk.Tk()
    root.geometry('300x150')
    
    radiobutton_variable = tk.StringVar()
    radiobutton_variable.set(1)
    
    # define a variable to store the current button state
    # (you could also set this to '1', but doing it this way means you won't have to
    #  update the default value in two places in case you decide to change it above!)
    prev_btn = radiobutton_variable.get()
    
    button_1 = tk.Radiobutton(root, text='Button 1', variable=radiobutton_variable, value=1, command=on_choice)
    button_2 = tk.Radiobutton(root, text='Button 2', variable=radiobutton_variable, value=2, command=on_choice)
    
    button_1.pack()
    button_2.pack()
    
    root.mainloop()