繁体   English   中英

初始化单选按钮Tkinter

[英]Initializing Radio Buttons Tkinter

我正在尝试为带有四个选项的问题创建一个选择菜单。 我实例化了四个单选按钮,每个选择一个。 由于某种原因,当窗体出现时,已经选择了最后三个。 当您单击一个按钮时,仅该按钮被选中,而其他按钮则被取消选择。 我想要这样,所以表格的原始版本没有选择任何一个。

            self.radio_button_frame = Frame(self)
            self.radio_button_frame.grid(row=1, column=1, rowspan=4)
            self.correct_label = Label(self, text="Correct: " + str(self.health_regain), width=25, justify=RIGHT)
            self.correct_label.grid(row=0, column=3)
            #space the image so it takes up 4 rows
            self.hydra_label.grid_forget()
            self.hydra_label.grid(row=0, column=0, rowspan=6)

            #get the question
            self.question = self.question_base.get_question()
            self.answer = 0

            #get rid of the begin button
            self.begin_button.grid_forget()

            #create radio buttons for each question choice
            self.description_label.config(text=self.question.question)
            self.radio_button_1 = Radiobutton(self.radio_button_frame, text=self.question.choice_a, padx=10, value=0, justify=LEFT, variable= self.answer)
            self.radio_button_1.pack(anchor=W)
            self.radio_button_2 = Radiobutton(self.radio_button_frame, text=self.question.choice_b, padx=10, value=1, justify=LEFT, variable= self.answer)
            self.radio_button_2.pack(anchor=W)
            self.radio_button_3 = Radiobutton(self.radio_button_frame, text=self.question.choice_c, padx=10, value=2, justify=LEFT, variable= self.answer)
            self.radio_button_3.pack(anchor=W)
            self.radio_button_4 = Radiobutton(self.radio_button_frame, text=self.question.choice_d, padx=10, value=3, justify=LEFT, variable= self.answer)
            self.radio_button_4.pack(anchor=W)
            self.answer_button = Button(self, text="Answer")
            self.answer_button.grid(row=5, column=1, columnspan=2)

您需要给Radiobutton的变量应该是Tkinters IntVar() 所以代替:

self.answer = 0

放:

self.answer = IntVar()           #We declare it like this
self.answer.set(-1)              #If you want none of your radionbuttons to be selected, give the IntVar value that isn't set in any Radiobutton.

要获取self.answer的价值,只需调用self.answer.get()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM