python - Tkinter 网格填充空白空间
问题描述
在发布之前我确实搜索了很多示例,但仍然无法正确使用 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()
解决方案
快速简单的解决方案是定义columnspan
. treeview
这将告诉树视图分布在 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()
结果:
要解决您在评论中提到的问题,您可以删除root.columnconfigure(0, weight=1)
以使条目正确展开。
推荐阅读
- python - 如何在按下按钮之前不断更新 tkinter 标签?
- javascript - 使用 Reducer 从数组中删除所有项目 - React
- wordpress - 在手动更新产品之前,产品数据更新无效 - woocommerce
- generics - 类型推断失败,但无法检查擦除类型的实例
- android - Android 窗口管理器报告不正确的物理尺寸
- python - Google API (Sheets) API 错误代码 403。权限不足:请求的身份验证范围不足
- azure - 如何批量下载 Azure Artifacts 包?
- xml - 使用 VBA 宏识别项目符号列表的样式类型
- java - 无法将 MySQL 数据库与 Eclipse Neon 连接
- verilog - 如何删除自动生成的 YOSYS 评论?