寻找 tkinter 错误和 efficiency/design 问题的解决方案

Looking for a solution to a tkinter error and efficiency/design problems

下面的代码代表我使用 tkinter 在 python 上制作计算器的第一步。这个想法是将数字相应地放在网格上,然后进行所有必要的调整。这里的问题是我收到以下错误: _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack 我知道这是因为 canvas.pack(),但这不是背景所必需的吗?我怎样才能以最有效的方式将它们分开?关于这一点,有没有办法使用更少的代码行将所有 buttons/grids 放在一起?提前致谢。

from tkinter import *

#Creating the window function (?)
window = Tk()

#Creating a frame and a background for the calculator
canvas = tk.Canvas(window, height=700, width=700, bg="#83CFF1")
canvas.pack()

frame = tk.Frame(window, bg="white")
frame.place(relwidth=0.7, relheight=0.7, relx=0.15, rely=0.15)

#Creating the buttons for the calculator
button1 = Label(window, text="1")
button2 = Label(window, text="2")
button3 = Label(window, text="3")
button4 = Label(window, text="4")
button5 = Label(window, text="5")
button6 = Label(window, text="6")
button7 = Label(window, text="7")
button8 = Label(window, text="8")
button9 = Label(window, text="9")
button0 = Label(window, text="0")

#Adding it to the screen
button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
button3.grid(row=0, column=2)
button4.grid(row=1, column=0)
button5.grid(row=1, column=1)
button6.grid(row=1, column=2)
button7.grid(row=2, column=0)
button8.grid(row=2, column=1)
button9.grid(row=2, column=2)
button0.grid(row=3, column=1)

#Ending the loop (?)
window.mainloop()
  • 使用 Python 列表 comprehension 创建 buttons
  • 对于网格布置,在 for 循环中使用 i // 3(底除法)和 i % 3(取模)。
  • 然后只需手动添加最后一个按钮即可。

下面这段代码可以解决问题:

import tkinter as tk

window = tk.Tk()

frame = tk.Frame(window, bg="white")
frame.place(relwidth=0.7, relheight=0.7, relx=0.15, rely=0.15)

#Creating the buttons for the calculator
buttons = [tk.Button(frame, text = i) for i in range(1, 10)]


for i, button in enumerate(buttons):
    button.grid(row =  i // 3, column = i % 3)

#Add last button 0
buttons.append(tk.Button(frame, text = 0))
buttons[-1].grid(row=3, column=1)

window.mainloop()