用tkinter单选按钮创建自我报告调查问卷

问题描述:

我想用tkinter创建自我问卷调查问卷。这个问卷有很多问题,对于每个问题,用户应该使用0到4之间的数值进行回应(其中“0”代表“绝对不”,而“4”代表“绝对是”)用tkinter单选按钮创建自我报告调查问卷

我使用Labels来打包问题和Radiobutton以获取用户的响应。

我想要做的是获得每个问题,首先是特定问题的索引,然后是用户选择的相对响应。下面的代码的一部分,当我创建响应单选按钮:

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() 
然而

...当我测试,如果代码工作通过点击单选按钮,我总是得到什么单选按钮我不惜一切问题选择相同的输出I回应:

>>> 
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 

任何人都可以帮助我吗?

在此先感谢

这是一个常见的问题的人一个循环内控制指定command时面对的问题。所有单选按钮的命令中都使用相同的值i,即使它们在创建时都有不同的值。有关变量绑定行为的深入解释,请参见Local variables in Python nested functions。实际的解决方案是提供i作为默认参数:

command= lambda i=i: self.get_resp(
       self.question_index[i], 
       self.var_list[i] 
       ),