Tkinter按钮命令无法使用lambda exec命令

时间:2018-01-26 10:04:11

标签: python tkinter lambda

我是Python的初学者和一般的编码,我无法获得第二个按钮来运行它的命令,其中包含字符串" self.terminate"在这里执行(只有第二个按钮不起作用,第一个按钮工作正常)

 c.execute("SELECT buttonText, buttonCommand FROM buttons WHERE buttonWindow=?", (frameWindow,))

 buttonValues = c.fetchall()

 for row in buttonValues:
      self.buttonRows.append(tk.Button(self, text = row[0], command = lambda self=self, buttonCommand = row[1]: exec(buttonCommand))
                             .grid(column = 0, row = self.iterationRow, padx = 10, pady = 10))
      self.iterationRow += 1  

终止定义:

def terminate(self):
      conn.close()

      root.destroy()

它什么也没做。你能帮助我吗?感谢

1 个答案:

答案 0 :(得分:0)

假设您的数据库的值为self.terminate,则需要在调用()时附加exec(即:您需要exec("self.terminate()")而不是exec("self.terminate")

我的建议是不要尝试将这么多代码包装成一行。正如您所知,它使调试变得非常困难。您应该为按钮创建一个合适的功能。

例如:

for row in buttonValues:
    button = tk.Button(self, text=row[0], command=lambda cmd=row[1]: self.do_command)
    button.grid(column=0, row=self.iterationRow, padx=10, pady=10)
    self.buttonRows.append(button)
...
def do_command(self, command):
    cmd = command + "()"
    exec(cmd)

这使得理解和调试变得更加容易。

所有这一切,在数据库中存储按钮的字符串表示似乎是一个非常值得怀疑的设计。我没有看到你做这件事有什么价值。

相关问题