我正在使用tkinter创建一个GUI计算器程序,我想知道是否可以创建按钮而不会使我的代码变得过长(因为我的程序将包含许多执行相同功能但使用的按钮参数的值不同。)
代码:
self.divide = tk.Button(self, text = "/", width = 4, command = lambda: self.process("/"))
self.divide.grid(row = 2, column = 3)
self.multiply = tk.Button(self, text = "*", width = 4, command = lambda: self.process("*"))
self.multiply.grid(row = 3, column = 3)
self.minus = tk.Button(self, text = "-", width = 4, command = lambda: self.process("-"))
self.minus.grid(row = 4, column = 3)
self.add = tk.Button(self, text = "+", width = 4, command = lambda: self.process("+"))
self.add.grid(row = 5, column = 3)
如何减少重复此代码?
答案 0 :(得分:3)
你可以进行buttons
迭代 - 我建议dict
。例如
self.buttons = {}
for i, operation in enumerate(['/','*','-','+']):
self.buttons[operation] = tk.Button(self, text = operation,
width = 4, command = lambda: self.process(operation))
self.buttons[operation].grid(row = i+2, column = 3)
这适用于给定的具体示例,但可能非常重要。