我试图在python中创建一个应用程序。大多数情况下,除了第一个之外的所有单选按钮都已被选中,并且在悬停之后选择了第一个单选按钮。请注意,这种情况在10次中有9次发生,并且一旦按预期工作。
代码包括在下面。 编辑:代码重新编写。我认为它在复制粘贴期间发生了变化。遗憾!
import sys
from Tkinter import *
i = 0
#for i in range(0, 10):
# print i
macro_sheet_names = [1, 2, 3, 4]
print len(macro_sheet_names)
root = Tk()
var = IntVar()
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
print ('Tab selected: ' + str(var.get()))
root.destroy()
# sys.exit()
# root.withdraw()
i = 0
for i in range (0, len(macro_sheet_names)):
R = Radiobutton(root, text = macro_sheet_names[i], variable = var, value = i, command = sel)
R.pack(anchor = W)
label = Label(root)
label.pack()
root.mainloop()
print ('Exiting...')
sys.exit()
答案 0 :(得分:1)
对我来说,它可以在Python 3上进行修改。试试这个:
import sys
from Tkinter import *
i = 0
#for i in range(0, 10):
# print i
macro_sheet_names = [1, 2, 3, 4]
print (len(macro_sheet_names))
root = Tk()
var = IntVar()
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
print ('Tab selected: ' + str(var.get()))
root.destroy()
# sys.exit()
# root.withdraw()
i = 0
for i in range (0, len(macro_sheet_names)):
R = Radiobutton(root, text = macro_sheet_names[i], variable = var, value = i, command = sel)
if i == 0: R.select ()
R.pack(anchor = W)
label = Label(root)
label.pack()
root.mainloop()
print ('Exiting...')
sys.exit()
它只是自动选择第一个收音机。