我正在尝试使用包含单选按钮的 tkinter 实现一个菜单,但在单击其中一个选项之前我无法选择其中一个选项。当 GUI 出现时,没有选择任何单选按钮,而是我希望选择第二个选项。这是我的代码:
menubar = Menu(root)
# create a pulldown menu, and add it to the menu bar
settings = Menu(menubar, tearoff=0)
settings.add_command(label='some 1', command=some_1)
settings.add_command(label='some 2', command=some_2)
mDebug = Menu(settings, tearoff=0)
rvar = IntVar(root)
rvar.set(1)
mDebug.add_radiobutton(label='first', var = rvar, value = 0)
mDebug.add_radiobutton(label='second', var = rvar, value = 1)
mDebug.add_radiobutton(label='third', var = rvar, value = 2)
settings.add_cascade(label='radio options', menu = mDebug)
settings.add_separator()
settings.add_command(label='quit', command=close)
menubar.add_cascade(label="Menu", menu=settings)
root.config(menu=menubar)
编辑:这是代码的更完整版本:
from tkinter import *
def change(idx):
print(idx)
def show_menu(root):
menubar = Menu(root)
settings = Menu(menubar, tearoff=0)
settings.add_command(label='some 1')
settings.add_command(label='some 2')
mDebug = Menu(settings, tearoff=0)
rvar = IntVar(root)
rvar.set(1)
mDebug.add_radiobutton(label='first', var = rvar, value = 0, command=lambda idx=0: change(idx))
mDebug.add_radiobutton(label='second', var = rvar, value = 1, command=lambda idx=1: change(idx))
mDebug.add_radiobutton(label='third', var = rvar, value = 2, command=lambda idx=2: change(idx))
settings.add_cascade(label='radio options', menu = mDebug)
settings.add_separator()
settings.add_command(label='quit')
menubar.add_cascade(label="Menu", menu=settings)
root.config(menu=menubar)
root = Tk()
show_menu(root)
root.mainloop()