您想要做的事情有些复杂,因此即使您不只是学习如何使用 tkinter 也可能具有挑战性(只是因为它的文档记录太差而加剧了这种情况)。因此,我创建了一个示例,说明如何根据您问题中的代码进行操作。
(对我来说)一件不直观的事情是 Event 处理窗口的 <'Configure>' 事件的“回调”函数会被窗口本身调用以及其中的所有小部件 - 如果您没有意识到这就是发生的事情,这可能会非常令人困惑。
我还更改并重新格式化了您的代码,以更紧密地遵循PEP 8 - Style Guide for Python Code 的建议,我强烈建议您阅读并开始关注这些建议。请特别注意,我将您的通配符 from tkinter import * 更改为首选的 import tkinter as tk — 请参阅 Should wildcard import be avoided?
import tkinter as tk
WIDTH, HEIGHT = 1366, 768 # Initial size of root window.
class InventorySystem:
# Gradient frame colors.
COLORS = ["#007F5F", "#2B9348", "#55A630", "#80B918", "#AACC00",
"#BFD200", "#D4D700", "#DDDF00", "#EEEF20", "#FFFF3F"]
def __init__(self, root):
self.root = root
self.root.title("Inventory System")
self.root.geometry(f'{WIDTH}x{HEIGHT}')
self.width, self.height = WIDTH, HEIGHT # Size of root window.
self.create_gradient_frames()
def create_gradient_frames(self):
"""Create a gradient frame for each color."""
self.gradient_frames = []
colors = self.COLORS # Alias for local access.
gradient_frame_width = round(self.width / len(colors))
gradient_frame_height = self.height
for i, color in enumerate(colors):
frame = tk.Frame(self.root, width=gradient_frame_width,
height=gradient_frame_height, bg=color)
frame.place(x=i * gradient_frame_width,
y=self.height - gradient_frame_height)
self.gradient_frames.append(frame)
def update_gradient_frames(self):
"""Update size and position of all gradient frames."""
gradient_frame_width = round(self.width / len(self.COLORS))
gradient_frame_height = self.height
for i, frame in enumerate(self.gradient_frames):
frame.config(width=gradient_frame_width, height=gradient_frame_height)
frame.place(x=i * gradient_frame_width,
y=self.height - gradient_frame_height)
def on_resize(self, event):
"""Root window size change event handler."""
# Needed following because event handler is called for the container win
# and all its child widgets but we only need to handle container itself.
if event.widget.master is not None: # Not the root window?
return # Ignore.
width, height = root.winfo_width(), root.winfo_height() # Current size.
if width != self.width or height != self.height: # Updated?
self.width, self.height = width, height # Track change.
self.update_gradient_frames()
if __name__ == "__main__":
root = tk.Tk()
application = InventorySystem(root)
root.bind('<Configure>', application.on_resize) # Bind callback function to event.
root.mainloop()
这是正在调整大小的窗口的屏幕截图: