如何从for循环中创建的Tkinter单选按钮组中获取值

2024-04-16 15:54:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个Notebook的不同选项卡中自动创建几个4Radiobuttons的组,每个选项卡的内容都是在for循环中创建的,并对它们使用trace_add,但它不起作用

下面是我的代码的示例:

test_type_vars = []
for test_name in ["idvg0", "idvgh", "idvd0", "idvdh", "acvg0", "acvgh", "acfreq0", "noise"]:
        test_type_frame= Frame(notebook, name=test_name+"_frame")
        notebook.add(test_frame, text=test_name)
        type_var = IntVar()
        type_var.set(random.randint(1,4))
        test_type_vars.append(type_var)
        dc_type_radio = Radiobutton(test_type_frame, text="DC", variable=type_var, value=1)
        dc_type_radio.pack(side=LEFT, padx=10)
        ac_type_radio = Radiobutton(test_type_frame, text="AC", variable=type_var, value=2)
        ac_type_radio.pack(side=LEFT, padx=10)
        acfreq_type_radio = Radiobutton(test_type_frame, text="ACFREQ", variable=type_var, value=3)
        acfreq_type_radio.pack(side=LEFT, padx=10)
        noise_type_radio = Radiobutton(test_type_frame, text="Noise", variable=type_var, value=4)
        noise_type_radio.pack(side=LEFT, padx=10)

for var in test_type_vars:
    print(var.get())
    var.trace_add("write", change_test_type)

def change_test_type(var, blank, mode):
    print("FLAG")

问题是,当我更改单选按钮选择时,从未调用change_test_类型,也从未看到“标志”,但我看到随机数正在打印。我不明白为什么它不起作用,也许我只是犯了一个愚蠢的错误

谢谢