【发布时间】:2021-11-13 17:11:00
【问题描述】:
我现在正在练习框架设置在 tkinter 中的动态性。
对于纯框架设置,它看起来很完美:
import tkinter as tk
class MyWindow:
def __init__(self, root):
w_root = 1280
h_root = 720
root.title('My model')
root.geometry(f"{w_root}x{h_root}")
self.top_frame = tk.Frame(root, width=w_root, height=80, bg='grey')
self.top_frame.grid(row=0, column=0, padx=0, pady=5)
self.main_frame = tk.Frame(root, width=w_root, height=640, bg='blue')
self.main_frame.grid(row=1, column=0, padx=0, pady=0)
self.left_frame = tk.Frame(self.main_frame, width=500, height=620, bg='red')
self.left_frame.grid(row=0, column=0, padx=5, pady=5)
self.right_frame = tk.Frame(self.main_frame, width=760, height=620, bg='yellow')
self.right_frame.grid(row=0, column=1, padx=5, pady=5)
root = tk.Tk()
mywin = MyWindow(root)
root.mainloop()
但是,当我尝试在left_frame(主框架内的框架)中放置标签时,界面变得奇怪:
import tkinter as tk
class MyWindow:
def __init__(self, root):
w_root = 1280
h_root = 720
root.title('My model')
root.geometry(f"{w_root}x{h_root}")
self.top_frame = tk.Frame(root, width=w_root, height=80, bg='grey')
self.top_frame.grid(row=0, column=0, padx=0, pady=5)
self.main_frame = tk.Frame(root, width=w_root, height=640, bg='blue')
self.main_frame.grid(row=1, column=0, padx=0, pady=0)
self.left_frame = tk.Frame(self.main_frame, width=500, height=620, bg='red')
self.left_frame.grid(row=0, column=0, padx=5, pady=5)
self.right_frame = tk.Frame(self.main_frame, width=760, height=620, bg='yellow')
self.right_frame.grid(row=0, column=1, padx=5, pady=5)
self.lb_currdate = tk.Label(self.left_frame, text='my lable1:')
self.lb_currdate.config(font=('Arial', 9))
self.lb_currdate.grid(row=0,column=0, padx=5, pady=5)
self.ent_currdate = tk.Entry(self.left_frame)
self.ent_currdate.insert(tk.END, str(0))
self.ent_currdate.grid(row=0,column=1, padx=5, pady=5)
root = tk.Tk()
mywin = MyWindow(root)
root.mainloop()
我希望框架看起来相同,并且标签和条目将在红色框架(左框架)的顶部移动。
我对此感到很困惑,有人可以提示我哪一行代码是错误的吗?
谢谢
#-----更新-----
根据建议,我在网格中加入了粘性。 它看起来好多了,但仍然没有达到我预期的 100%。我尝试了不同的粘性组合,但没有一个是正确的:
Test1(给左框架粘性):
self.left_frame.grid(row=0, column=0, padx=5, pady=5, sticky=tk.N + tk.E + tk.S + tk.W)
大型机没有填满 enti
Test2(让左框架和主框架都具有粘性):
self.main_frame.grid(row=1, column=0, padx=0, pady=0, sticky=tk.N + tk.E + tk.S + tk.W)
self.left_frame.grid(row=0, column=0, padx=5, pady=5, sticky=tk.N + tk.E + tk.S + tk.W)
左边框和右边框没有填满主边框
【问题讨论】:
-
sticky选项是告诉布局管理器如何占用一行或一列的可用空间。但是,您需要使用.rowconfigure()和.columnconfigure()告诉布局管理器要为列或行分配多少空间。