【问题标题】:Tkinter grid fill empty spaceTkinter 网格填充空白空间
【发布时间】:2021-07-26 13:17:34
【问题描述】:

我在发布之前确实搜索了很多示例,但仍然无法正确使用 tkinter 网格。

我想要什么:

我的代码:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

b1 = ttk.Button(root, text='b1')
b1.grid(row=0, column=0, sticky=tk.W)

e1 = ttk.Entry(root)
e1.grid(row=0, column=1, sticky=tk.EW)

t = ttk.Treeview(root)
t.grid(row=1, column=0, sticky=tk.NSEW)

scroll = ttk.Scrollbar(root)
scroll.grid(row=1, column=1, sticky=tk.E+tk.NS)

scroll.configure(command=t.yview)
t.configure(yscrollcommand=scroll.set)

root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
root.rowconfigure(1, weight=1)

root.mainloop()

【问题讨论】:

  • t.grid(row=1, column=0, sticky=tk.NSEW) 更改为t.grid(row=1, column=0, columnspan=2, sticky=tk.NSEW)
  • 谢谢,这修复了树视图和滚动条,但在调整窗口大小时条目仍然有空白。
  • 您希望输入字段随窗口一起扩展?
  • 它已经随着窗口向右侧展开,但它离按钮很远。
  • 这是因为您在第 0 行设置的权重。您可以通过删除 root.columnconfigure(0, weight=1) 来解决此问题。看我的回答。

标签: python tkinter grid-layout


【解决方案1】:

快速简单的解决方案是定义treeviewcolumnspan。这将告诉树视图分布在 2 列中,并允许输入字段位于您的按钮旁边。

在不相关的注释中,您可以为您的sticky 使用字符串,这样您就不必执行tk.E+tk.NS 之类的操作。相反,只需使用"nse" 或您需要的任何指示。确保认为您是按照"nsew" 的顺序进行操作的。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

b1 = ttk.Button(root, text='b1')
b1.grid(row=0, column=0, sticky="w")

e1 = ttk.Entry(root)
e1.grid(row=0, column=1, sticky="ew")

t = ttk.Treeview(root)
t.grid(row=1, column=0, columnspan=2, sticky="nsew") # columnspan=2 goes here.

scroll = ttk.Scrollbar(root)
scroll.grid(row=1, column=2, sticky="nse") # set this to column=2 so it sits in the correct spot.

scroll.configure(command=t.yview)
t.configure(yscrollcommand=scroll.set)

# root.columnconfigure(0, weight=1) Removing this line fixes the sizing issue with the entry field.
root.columnconfigure(1, weight=1)
root.rowconfigure(1, weight=1)

root.mainloop()

结果:

要解决您在 cmets 中提到的问题,您可以删除 root.columnconfigure(0, weight=1) 以使条目正确展开。

【讨论】:

  • 非常感谢迈克,我自己永远不会这样做 :)
  • @VítorNunes 确定。如果我的回答解决了您的问题,请确保通过选中我的回答旁边的复选标记来表明您的问题已得到解决。
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多