我正在尝试使用 Python 中的 Tkinter 制作一个计算器。我使用 for 循环来绘制按钮,并且尝试使用 lambda 函数,以便仅在按下按钮时调用按钮的操作,而不是在程序启动时立即调用。然而,当我尝试这样做时,会抛出“列表索引超出范围”错误。
这是绘制按钮并设置其过程的相关部分:
# button layout
# ( ) AC **
# 7 8 9 /
# 4 5 6 *
# 1 2 3 -
# 0 . = +
# list that holds the buttons' file names in order
imgOrder = ["lpr", "rpr", "clr", "pow",
"7", "8", "9", "div",
"4", "5", "6", "mul",
"1", "2", "3", "sub",
"0", "dot", "eql", "add"];
# list containing the actual values assigned to buttons in order
charOrder = ["(", ")", "AC", "**",
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"];
imgIndex = 0;
for rowi in range(1, 6):
for coli in range(4):
# fetch and store the img
img = PhotoImage(file="images/{}.gif".format(imgOrder[imgIndex]));
# create button
button = Button(self, bg="white", image=img,
borderwidth=0, highlightthickness=0, activebackground="white",
command=lambda: self.process(charOrder[imgIndex]));
# set button image
button.image = img;
# put the button in its proper row and column
button.grid(row=rowi, column=coli, sticky=N+S+E+W);
imgIndex += 1;
# pack the GUI
self.pack(fill=BOTH, expand=1);
# processes button presses
def process(self, button):
print("Button {button} pressed!");
# AC clears the display
if (button == "AC"):
# clear
self.display["text"] = "";
# otherwise, the number/operator can be tacked on the end
else:
self.display["text"] += button;
具体来说,引发错误的行是带有 lambda 函数的行,但我不知道有什么方法可以只让按钮在单击时注册,而不需要单独为每个按钮写出此块。