TkDocs网站是一个很好的资源,但它并不完整。手册页是完整的,但当然没有记录 Python 绑定。“如何在 Tkinter 中获取屏幕大小? ”指出可以使用 root.winfo_screenwidth() / root.winfo_screenheight() 获取窗口大小,但这仅针对整个窗口,而不是网格中的单个单元格。
以 TkDocs 代码为例,我怎样才能找到例如第三行的高度,以便我可以设置一个最小尺寸来防止按钮被隐藏?我尝试使用 bbox() 或 grid_bbox() 没有返回 (0,0,0,0) 以外的任何内容。返回实际大小的正确语法是什么?
- - - 编辑 - - -
代码现在显示如何在从事件循环调用的例程中使用 bbox(),并返回正确的值。
from tkinter import *
from tkinter import ttk
# bbox() works after window has been rendered
def e_config(event):
w, h = event.width, event.height
print("Resize: content", w, "x", h)
print("content bbox=", content.bbox())
def OK():
print("OK: winfo, bbox:")
print(" root: ", root.winfo_width(), root.winfo_height(), root.bbox())
print(" content: ", content.winfo_width(), content.winfo_height(), content.bbox())
print(" frame: ", frame.winfo_width(), frame.winfo_height(), frame.bbox())
root = Tk()
content = ttk.Frame(root, padding=(5,5,12,12))
content.bind("<Configure>", e_config)
frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100)
namelbl = ttk.Label(content, text="Name")
name = ttk.Entry(content)
onevar = BooleanVar()
twovar = BooleanVar()
onevar.set(True)
twovar.set(False)
one = ttk.Checkbutton(content, text="One", variable=onevar, onvalue=True)
two = ttk.Checkbutton(content, text="Two", variable=twovar, onvalue=True)
ok = ttk.Button(content, text="Okay", command=OK)
cancel = ttk.Button(content, text="Cancel")
content.grid(column=0, row=0, sticky=(E, W)) # Don't resize vertically
frame.grid(column=0, row=0, columnspan=3, rowspan=2)
namelbl.grid(column=3, row=0, columnspan=2)
name.grid(column=3, row=1, columnspan=2)
one.grid(column=0, row=3)
two.grid(column=1, row=3)
ok.grid(column=3, row=3)
cancel.grid(column=4, row=3)
root.configure(bg="#234")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
content.columnconfigure(0, weight=1)
content.columnconfigure(1, weight=1)
content.columnconfigure(2, weight=1)
content.columnconfigure(3, weight=1)
# This doesn't work - screen hasn't been rendered yet
print("pre-init bbox ", content.bbox())
root.mainloop()