寻找tkinter错误和效率/设计问题的解决方案



下面的代码代表了我使用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()
  • 使用Python列表comprehension创建buttons
  • 在For循环中使用i // 3(floordivision)和i % 3(modulo)来放置网格。
  • 然后只需手动添加最后一个按钮。

下面的代码可以达到这个目的:

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()

最新更新