【问题标题】:Python - Tkinter RadioButton If StatementPython - Tkinter RadioButton If 语句
【发布时间】:2014-01-18 15:23:55
【问题描述】:

我有一个单选按钮,可以让我选择 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()

【问题讨论】:

    标签: python if-statement tkinter


    【解决方案1】:

    您可以使用 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()
    

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 2018-10-07
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      相关资源
      最近更新 更多