Python - Tkinter RadioButton If 语句

标签 python if-statement tkinter

我有一个单选按钮,可以让我选择 0、1 或 2。以下脚本在终端中打印 0、1 或 2,但我希望它根据我选择的内容执行“操作”。

例如,如果我选择 0,我希望它执行 root.destroy() 如果我选择 1,我希望它做其他事情等等。

我以为我需要声明一个全局变量,但它似乎不起作用。

这是脚本。

root = Tk()

v = IntVar()
v.set(0)  # set to 0 pics as default. Just looks prettier...

languages = [
    ("0 Pics",0),
    ("1 Pic",1),
    ("2 Pics",2),
]

def ShowChoice():
    world = v.get()
    global world
    print world

Label(root, text="""How many pictures do you have left to scan?""", padx = 15).pack()

for txt, val in languages:
    Radiobutton(root, 
                text=txt,
                padx = 20, 
                variable=v, 
                command=ShowChoice,
                value=val).pack(anchor=W)

mainloop()

Radiobutton(root, 
            text=txt,
            indicatoron = 0,
            width = 20,
            padx = 20, 
            variable=v, 
            command=ShowChoice,
            value=val).pack(anchor=W)


print 'The V get variable is: ' + world()

最佳答案

您可以使用 lambda 来传递带参数的函数。

for txt, val in languages:
    Radiobutton(root, 
                text=txt,
                padx = 20, 
                variable=v, 
                command=lambda: ShowChoice(root),
                value=val).pack(anchor=W)

在 ShowChoice 函数中,只需使用 if/else 即可根据所选内容执行“操作”。 例如。

def ShowChoice(root):
    world = v.get()
    if world == 0:
       root.destroy()

关于Python - Tkinter RadioButton If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21206030/

相关文章:

Python - copy.copy() 的元素是否仍与原始元素共享内存?

python - 引导操作成功后,节点预配器中的EMR从引导失败

python - 为分配给一行值的列表列表中的元素分配一个值

if-statement - 我应该如何在 web assembly 中实现 "else if"?

python - 如何使用多个 if 条件创建 for 循环

python - 由于自定义标题栏,应用程序的图标未显示在任务栏中?

python - 如何使用对象的方法从列表中删除对象?

python - 如何关闭日志缓冲区以使用python命令行工具实时获取日志?

excel - 嵌套的 IF/AND 语句

python-2.7 - PyInstaller 在 Windows 7 : "Can' t find a usable init. tcl 上失败”