Tkinter:Frame类内创建多个独立子框架的重叠问题求助
Hey there, I see exactly what's causing your overlapping components—let's get this sorted out quickly!
The Core Issue
You've created frame1 and frame2 as child frames of MainPage, but here's the mistake: all your widgets (labels, entries, buttons) are being attached directly to self (the MainPage) instead of their respective sub-frames. That means your widgets aren't actually inside frame1 or frame2 at all—they're floating directly on top of the MainPage, so their grid positions are relative to the MainPage, leading to overlaps.
Corrected Code
Here's the fixed version of your MainPage class:
class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # First frame inside MainPage frame1 = tk.Frame(self, bg="red") frame1.grid(row=0, column=0, sticky="W") # Attach label to frame1, not self frame1.label = tk.Label(frame1, text="Main Page", font=SMALL_FONT) frame1.label.grid(row=0, column=0, sticky="W") itemScanNumber = tk.StringVar() # Attach entry to frame1 frame1.EntryBox = ttk.Entry(frame1, textvariable=itemScanNumber) frame1.EntryBox.grid(row=0, column=1, sticky="W") def printNumber(): print("Your Number: " + itemScanNumber.get()) # Attach buttons to frame1 frame1.button = ttk.Button(frame1, text="CLICK ME FOR SCAN NUMBER!", command=printNumber) frame1.button.grid(row=0, column=2, sticky="W") frame1.button1 = ttk.Button(frame1, text="CLICK ME!", command=lambda: controller.show_frame(MasterFilePage)) frame1.button1.grid(row=0, column=3, sticky="W") # Second frame inside MainPage frame2 = tk.Frame(self, bg="blue") frame2.grid(row=1, column=0, sticky="W") # Attach label to frame2, not self frame2.label = tk.Label(frame2, text="Main Page2", font=SMALL_FONT) frame2.label.grid(row=0, column=0, sticky="W")
Key Changes Explained
- For every widget that belongs to
frame1(label, entry, buttons), I changed their parent fromselftoframe1 - For the
frame2label, changed parent fromselftoframe2 - Now each widget is properly contained within its sub-frame, and the sub-frames themselves are placed in separate rows (
row=0androw=1) of the MainPage, so they won't overlap anymore - The grid layout for widgets inside each sub-frame is now relative to that sub-frame, not the MainPage—so you can arrange them independently without worrying about conflicting with other sub-frames
This should resolve the overlapping issue completely. Give it a test, and let me know if you run into any other snags!
内容的提问来源于stack exchange,提问作者Miggy

