“=”按钮应该位于 9,6,3 列,而无论我做什么,它只是不断被推到右侧的“+”按钮中。这是代码:
import tkinter as tk
import math
# Create the main window
root = tk.Tk()
root.title("Simple Calculator")
# Define button height, width, and padding
BUTTON_HEIGHT = 2
BUTTON_WIDTH = 5
BUTTON_PADDING = (10, 0) # Padding from top
# Create entry widget
entry = tk.Entry(root, width=20, font=("Arial", 14))
entry.grid(row=0, column=0, columnspan=5, pady=BUTTON_PADDING) # Add some padding to top
def button_click(value):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, current + value)
def clear():
entry.delete(0, tk.END)
def calculate():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(0, str(result))
except Exception as e:
entry.delete(0, tk.END)
entry.insert(0, "Error")
def square_root():
try:
value = float(entry.get())
result = math.sqrt(value)
entry.delete(0, tk.END)
entry.insert(0, str(result))
except Exception as e:
entry.delete(0, tk.END)
entry.insert(0, "Error")
# Create clear button to the left of the % button
tk.Button(root, text='C', width=BUTTON_WIDTH, height=BUTTON_HEIGHT, command=clear).grid(row=1, column=0)
# Create % button above the number buttons in the top-left corner
tk.Button(root, text='%', width=BUTTON_WIDTH, height=BUTTON_HEIGHT, command=lambda: button_click('%')).grid(row=1, column=1)
# Create square root button to the right of the % button
tk.Button(root, text='√', width=BUTTON_WIDTH, height=BUTTON_HEIGHT, command=square_root).grid(row=1, column=2)
# Create buttons for numbers
numbers = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3',
'.', '0', '='
]
row_num = 2
col_num = 0
for number in numbers:
if number == '=':
tk.Button(root, text=number, width=BUTTON_WIDTH, height=BUTTON_HEIGHT, command=calculate).grid(row=row_num, column=col_num, columnspan=2)
col_num += 2 # Increment column number by 2
else:
tk.Button(root, text=number, width=BUTTON_WIDTH, height=BUTTON_HEIGHT, command=lambda value=number: button_click(value)).grid(row=row_num, column=col_num)
col_num += 1
if col_num > 2: # Check if column number exceeds 2
col_num = 0 # Reset column number
row_num += 1 # Move to the next row
# Create buttons for operations
operations = [
'/', '*', '-', '+',
]
# Update the initial row and column numbers for operation buttons
row_num = 2
col_num = 3
for operation in operations:
tk.Button(root, text=operation, width=BUTTON_WIDTH, height=BUTTON_HEIGHT, command=lambda value=operation: button_click(value)).grid(row=row_num, column=col_num)
row_num += 1
# Run the main loop
root.mainloop()
我试图解决这个问题,但问题却变得越来越糟。如果有人愿意帮忙的话,那真的会有帮助(我什至尝试使用 ChatGPT 但问题无法解决)。
问题是由链式
columnspan=2
方法中添加 .grid
引起的:
for number in numbers:
if number == '=':
tk.Button(root, text=number, width=BUTTON_WIDTH, height=BUTTON_HEIGHT,
command=calculate).grid(row=row_num, column=col_num, columnspan=2)
摆脱它,一切都会好起来的。也就是说,您也许可以从更简单的设置中受益。循环遍历包含您的
buttons
的单个列表,然后从 command
中获取正确的 dict
:
# delete all between `def square_root()` and `def square_root()` and insert:
# list of lists (desired grid)
buttons = [
['C', '%', '√'],
['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['.', '0', '=', '+']
]
# dict with custom commands
custom_commands = {
'C': clear,
'%': lambda: button_click('%'),
'√': square_root,
'=': calculate
}
# skip n rows
row_skip = 1
# loop `buttons`, add `command` from `dict` (`default` for numbers), create `tk.Button`
for row, button_list in enumerate(buttons):
for column, button in enumerate(button_list):
command = custom_commands.get(button, lambda value = button: button_click(value))
tk.Button(root, text = button, width = BUTTON_WIDTH, height = BUTTON_HEIGHT,
command = command)\
.grid(row = row_skip + row, column = column)