1-你从不打电话给你的GUI
2-在函数内定义的变量具有局部作用域,不能在外部访问它们,除非您在全局范围内声明它们,并使用global来更改它们的值。在
以下内容符合您的预期:
如果没有选中单选按钮,click将打印0
选择“红色”单选按钮后,click打印1
选择“黄色”按钮后,click打印2
可以使用这些值将调用重定向到另一个函数。在import tkinter as tk
def do_nothing():
pass
def do_red():
print('doing the red thing')
def do_yellow():
print('doing the yellow thing')
def clicked():
print(f'clicked {selected.get()}')
v = selected.get()
if v == 0:
do_nothing()
elif v == 1:
do_red()
elif v == 2:
do_yellow()
else:
print('an error occurred, the wrong value was recieved')
def GUI():
global rad1, rad2, selected
window = tk.Tk()
window.title("Select First Color")
selected = tk.IntVar()
rad1 = tk.Radiobutton(window, text='RED', value=1, variable=selected)
rad2 = tk.Radiobutton(window, text='YELLOW', value=2, variable=selected)
button1 = tk.Button(window, text="Select", command=clicked)
button2 = tk.Button(window, text="Quit", command=window.destroy)
rad1.grid(column=0, row=0)
rad2.grid(column=1, row=0)
button1.grid(column=6, row=0)
button2.grid(column=6, row=1)
window.mainloop()
rad1, rad2, selected = None, None, None
GUI()
或者,可以使用类来避免全局变量:
^{pr2}$