debugging 如何制作一个Tkinter表和小部件后?

gupuwyp2  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(115)

我尝试在Tkinter中创建一个表,并且运行得很好。但是,任何在表后打包的小部件都不会生成,而是抛出一个错误。我该如何修复这个问题?
这是表代码:

class Table:
  def __init__(self,root,rows,columns,lst):
    for i in range(rows):
      for j in range(columns):
        self.e = Entry(root, width=20, font=('Arial',16,))
        self.e.grid(row=i, column=j)
        self.e.insert(END, lst[i][j])

这是表生成代码,之后:

thislist = [
      ("Title", name),
      ("Company Size", vol),
      ("Price per share", price)
    ]
    row_amount = 3
    col_amount = 2
    Table(root1, row_amount, col_amount, thislist)
    color = 'red' if percent < 0 else 'green' if percent > 0 else 'gray'
    Label(root1, text = str(percent) + '%', fg = color).pack()

这就是错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
    return self.func(*args)
  File "main.py", line 77, in search_function
    layout(name.upper())
  File "main.py", line 105, in layout
    Label(root1, text = str(percent) + '%', fg = color).pack()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 2396, in pack_configure
    self.tk.call(
_tkinter.TclError: cannot use geometry manager pack inside . which already has slaves managed by grid
jecbmhm3

jecbmhm31#

该错误显然告诉您,您在同一个父容器root1中同时使用了.grid()Table类中的所有入口小部件)和.pack()(显示百分比的标签),这是不允许的。
建议将这些入口小部件放在一个框架内,然后使用.pack() * 打包 * 此框架:

...
    # frame to hold the table
    frame = Frame(root1)
    frame.pack()
    # create table inside frame
    Table(frame, row_amount, col_amount, thislist)
    color = 'red' if percent < 0 else 'green' if percent > 0 else 'gray'
    Label(root1, text = str(percent) + '%', fg = color).pack()
...

相关问题