【发布时间】:2021-05-05 05:32:02
【问题描述】:
下面的代码代表了我使用 tkinter 在 python 上制作计算器的第一步。这个想法是将数字相应地放在网格上,然后进行所有必要的调整。这里的问题是我收到以下错误:
_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
我知道这是因为canvas.pack(),但背景不是必需的吗?我怎样才能以最有效的方式将它们分开?关于这一点,有没有办法使用更少的代码行将所有按钮/网格放在一起?提前致谢。
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()
【问题讨论】:
-
按钮应该是
frame的子级而不是window? -
您为什么需要
Canvas?Canvas主要用于在其上绘制形状。如果你只是想要一些背景颜色,你可以直接改变window的背景:window.configure(bg=...)。
标签: python tkinter calculator