【问题标题】:Python Tkinter: Abort Radio Button in command callbackPython Tkinter:命令回调中的中止单选按钮
【发布时间】:2019-12-30 00:53:03
【问题描述】:

我正在尝试为我的 Tkinter 应用程序中的一个单选按钮提供一点额外的安全性。我有一组单选按钮可以在位图编辑器上的位深度之间切换,其中一种模式会修改调色板,所以我想在执行操作之前与用户确认。这是我写的一个快速演示来说明这个问题:

# Radio Button Abort Test
# Mikumiku747 2019-12-30

import tkinter as tk
import tkinter.messagebox as tkmb

class Application():

    def __init__(self):
        # Create widgets
        self.root = tk.Tk()
        self.dummyvar = tk.IntVar(self.root, value=1)
        self.radio1 = tk.Radiobutton(self.root, text="Option 1 (Safe)",
                                     command=lambda: self.safecallback(1),
                                     var=self.dummyvar, value=1)
        self.radio2 = tk.Radiobutton(self.root, text="Option 2 (Safe)",
                                     command=lambda: self.safecallback(2),
                                     var=self.dummyvar, value=2)
        self.radio3 = tk.Radiobutton(self.root, text="Option 3 (Dangerous)",
                                     command=lambda: self.dangercallback(3),
                                     var=self.dummyvar, value=3)
        # Widget Layout
        self.radio1.pack()
        self.radio2.pack()
        self.radio3.pack()

    def safecallback(self, value):
        print("Safe Callback with value", value)

    def dangercallback(self, value):
        print("Dangerous callback, asking for confirmation:")
        # We need to confirm with the user before doing anything which would 
        answer = tkmb.askyesno("Perform dangerous action",
                               "Are you sure you want to perform this action? Unsaved data may be lost!")
        if answer:
            print("User confirmed, clear things out.")
        else:
            return

问题是在点击选项3后,即使用户在对话框中按下no,第三个选项仍然会被选中。这可能会造成混淆,因为这些单选按钮还会向用户传达有关编辑器状态的信息。有没有一种简单的方法可以撤消选择,还是我必须自己跟踪变量的先前值?

【问题讨论】:

标签: python tkinter radio-button


【解决方案1】:

您只需将dummyvar 设置为0 即可取消选择“单选按钮”的所有三个选项。这是代码末尾的修改:

    if answer:
        print("User confirmed, clear things out.")
    else:
        self.dummyvar.set(0)

【讨论】:

    猜你喜欢
    • 2013-12-18
    • 2015-04-30
    • 2023-02-24
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2016-06-10
    • 2013-04-19
    相关资源
    最近更新 更多