Python 使用tkinter单选按钮创建自我报告问卷
我想使用tkinter创建一份自我报告问卷。此问卷有许多问题,对于每个问题,用户应使用0到4之间的数值进行回答(其中“0”表示“绝对不”,而“4”表示“绝对是”) 我使用标签将问题和单选按钮打包,以供用户回复 我想做的是获得每个问题,首先是特定问题的索引,然后是用户选择的相对响应。以下是我创建响应单选按钮时的代码部分:Python 使用tkinter单选按钮创建自我报告问卷,python,tkinter,radio-button,Python,Tkinter,Radio Button,我想使用tkinter创建一份自我报告问卷。此问卷有许多问题,对于每个问题,用户应使用0到4之间的数值进行回答(其中“0”表示“绝对不”,而“4”表示“绝对是”) 我使用标签将问题和单选按钮打包,以供用户回复 我想做的是获得每个问题,首先是特定问题的索引,然后是用户选择的相对响应。以下是我创建响应单选按钮时的代码部分: class Questionnaire: ... # response alternatives (from 0 to 4) def add_resp
class Questionnaire:
...
# response alternatives (from 0 to 4)
def add_resps(self):
self.question_index = {}
self.var_list = []
for i in range(len(self.affs)): # "self.affs" is the list of questions
self.question_index[i] = i
var = IntVar()
self.var_list.append(var)
for r in range(len( self.resps )):
col_Resp = 5 # previous columns are occupied by questions
self.wNumResp = Radiobutton(self.affs_frame,
text=r,
variable= self.var_list[i],
value=r,
command= lambda: self.get_resp(
self.question_index[i],
self.var_list[i]
),
bg="white",
fg="black",
font='Arial 10 bold',
relief=SOLID)
self.wNumResp.grid(row=i, column=r+colRisp, sticky=N+E+S+W)
def get_resp(self, question, response ):
print 'question n.', question, 'user\'s response:', response.get()
然而。。。当我通过点击单选按钮来测试代码是否有效时,无论我在回答什么问题时选择了什么单选按钮,我都会得到相同的输出:
>>>
question n. 28 user's response: 0
question n. 28 user's response: 0
question n. 28 user's response: 0
question n. 28 user's response: 0
question n. 28 user's response: 0
question n. 28 user's response: 0
question n. 28 user's response: 0
question n. 28 user's response: 0
question n. 28 user's response: 0
有人能帮我吗
提前感谢这是人们在为循环内的控件指定
命令时经常遇到的问题。所有单选按钮在其命令中都将使用相同的i
,即使在创建它们时它们的值都不同。有关变量绑定行为的详细说明,请参见。实际解决方案是将providei
作为默认参数:
command= lambda i=i: self.get_resp(
self.question_index[i],
self.var_list[i]
),