【问题标题】:Looking for a solution to a tkinter error and efficiency/design problems寻找 tkinter 错误和效率/设计问题的解决方案
【发布时间】: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
  • 您为什么需要CanvasCanvas 主要用于在其上绘制形状。如果你只是想要一些背景颜色,你可以直接改变window的背景:window.configure(bg=...)

标签: python tkinter calculator


【解决方案1】:
  • 使用 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多