python - Tkinter 错误 : cannot use geometry manager grid inside . 已经有由包管理的从站

标签 python python-3.x tkinter

from tkinter import *
import random
import time
tk=Tk()
canvas=Canvas(tk,width=1000,height=1000)
canvas.pack()
i=0
x1=-50
y1=0
choice=None
canvas.create_text(500, 300, text="Choose one.", font='TNR 20 bold')
def car():
    choice='car'
    return choice


button1=Button(tk,text='car',width=10,command=car)
button1.grid(row=1,column=5)#I do not see anything wrong here
tk.mainloop()

如果您想知道为什么我有这么多未使用的变量,这只是我的代码的一部分。

这是我运行代码时所说的内容:

  
Traceback (most recent call last):
  File "(You dont need to know the file name)", line 180, in 
    button1.grid(row=1,column=5)

  File "C:\Users\()\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2223, in grid_configure
    + self._options(cnf, kw))

_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack

最佳答案

不能混合使用 pack()grid()
来自文档:

Warning: Never mix grid and pack in the same master window. Tkinter will happily spend the rest of your lifetime trying to negotiate a solution that both managers are happy with. Instead of waiting, kill the application, and take another look at your code. A common mistake is to use the wrong parent for some of the widgets.

您正在调用 canvas.pack(),但对于同一个 tk 对象,您添加一个 button 并在其上调用 grid() 函数。

关于python - Tkinter 错误 : cannot use geometry manager grid inside . 已经有由包管理的从站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51458657/

相关文章:

python - Pandas 识别的所有 dtypes 是什么?

Python:正则表达式搜索

python - 绘图标签位于 tkinter Canvas 上的图形之外

python - 改组一个词

python - 如何在 python 中的某个时间后退出递归 DFS 算法?

python - 1_000 和 100_000 是什么意思?

python - 是否有使用 Python 2/3 兼容源作为移植策略的大型项目?

python - 在python中将文件作为列表读取

python - 如何从 Tkinter 文本小部件读取文本

Python/Tkinter - 运行具有多个参数的函数的按钮不起作用