简体   繁体   English

之后如何制作 Tkinter 表和小部件?

[英]How to make a Tkinter table and widgets after?

I am trying to make a table in Tkinter, and that works just fine.我正在尝试在 Tkinter 中制作一张桌子,效果很好。 However, any widgets that are packed after the table are not generated and instead throw an error.但是,不会生成在表之后打包的任何小部件,而是会抛出错误。 How can I fix this?我怎样才能解决这个问题?

This is the table code:这是表格代码:

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

This is the table generating code and after:这是表生成代码和之后:

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

And this is the error:这是错误:

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

The error obviously tells you that you have use both .grid() (all entry widgets inside Table class) and .pack() (label showing percentage) inside same parent container root1 which is not allowed.该错误显然告诉您您在同一个父容器root1中同时使用了.grid()Table类中的所有条目小部件)和.pack() (显示百分比的标签),这是不允许的。

Suggest to put those entry widgets inside a frame instead and then pack this frame using .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()
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM