我正在尝试使用类创建一个 Radiobutton
集,但所有按钮都会在开始时进行检查
当我尝试在 Radiobutton
创建阶段输入变量时,我收到了一条错误消息。
from tkinter import *
SubTests = ['Test 1', 'Test 2', 'Test 3', 'Test 4', 'Test 5', 'Test 6', 'Test 7', 'Test 8', 'Test 9', 'Test 10']
class GUI:
def __init__(self, master=NONE):
self.master = master
rb = [NONE]*len(SubTests)
for i in range(len(SubTests)):
rb[i] = Radiobutton(master, text=SubTests[i], fg='black', value=i)
rb[i].grid(column=0, row=(2 + i), sticky=W, padx=5)
root = Tk()
root.geometry('940x550')
root.resizable(FALSE,FALSE)
root.title("GUI Template")
display = GUI(root)
root.mainloop()
应该会出现Radiobutton
的 Test1、Test2、...、Test10 未选中的情况,但它们并不是全部选中。
最佳答案
以下是如何设置按钮以及我命名为 choice
的 IntVar
变量,以保存与 Radiobutton
相对应的值目前“插入”(如果有)。我还通过在 self.
前缀上制作了它和 GUI
类实例的 rb
列表实例属性。这将使从类的其他方法引用它们成为可能,因为所有方法都会自动传递 self
作为它们的第一个参数。
为了演示如何使用这些实例属性,代码还利用了 command=
选项,Radiobutton
必须指定一个要在每个时间点调用的“回调”函数用户改变状态的时间。
from tkinter import *
SubTests = ['Test 1', 'Test 2', 'Test 3', 'Test 4', 'Test 5', 'Test 6', 'Test 7',
'Test 8', 'Test 9', 'Test 10']
class GUI:
def __init__(self, master=None):
self.master = master
self.choice = IntVar(value=-1) # Set to a value no button will produce.
self.rb = []
for i, subtest in enumerate(SubTests):
radio_btn = Radiobutton(master, text=subtest, fg='black', value=i,
variable=self.choice, command=self.btn_callback)
radio_btn.grid(column=0, row=i+2, sticky=W, padx=5)
self.rb.append(radio_btn)
def btn_callback(self):
choosen = self.choice.get() # Index of button pressed.
subtest = self.rb[choosen].cget('text') # Button's text.
print('You chose: {}'.format(subtest))
root = Tk()
root.geometry('940x550')
root.resizable(FALSE, FALSE)
root.title("GUI Template")
display = GUI(root)
root.mainloop()
关于python - Tkinter 单选按钮奇怪的外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58762954/