Tkinter网格填充空sp

2024-06-12 03:09:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想要的:

enter image description here

我的代码:

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

Tags: importtkinterconfigurecolumnroottkb1grid
1条回答
网友
1楼 · 发布于 2024-06-12 03:09:13

快速而简单的解决方案是定义treeviewcolumnspan。这将告诉treeview跨两列展开,并允许条目字段位于按钮旁边。

在一个不相关的注释中,可以使用字符串来表示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()

结果:

enter image description here

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

enter image description here

相关问题 更多 >