简体   繁体   中英

TKinter app - not showing frames in oop approach

Something must have gone wrong in my TKinter project when I restructured the code to conform to the OOP paradigm.

The MainFrame is no longer displayed. I would expect a red frame after running the code below, but it just shows a blank window.

import tkinter as tk
from tkinter import ttk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("App")
        self.geometry("800x600")

        main_frame = MainFrame(self)
        main_frame.tkraise()


class MainFrame(ttk.Frame):
    def __init__(self, container):
        super().__init__(container)
        s = ttk.Style()
        s.configure("top_frame.TFrame", background="red")
        self.my_frame = ttk.Frame(self, style="top_frame.TFrame")
        self.my_frame.pack(fill="both", expand=True)

if __name__ == "__main__":
  app = App()
  app.mainloop()

You should also manage the geometry of your MainFrame inside the App, for example by packing it:

import tkinter as tk
from tkinter import ttk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("App")
        self.geometry("800x600")

        main_frame = MainFrame(self)
        main_frame.pack(fill='both', expand=True)  # PACKING FRAME
        main_frame.tkraise()


class MainFrame(ttk.Frame):
    def __init__(self, container):
        super().__init__(container)
        s = ttk.Style()
        s.configure("top_frame.TFrame", background="red")
        self.my_frame = ttk.Frame(self, style="top_frame.TFrame")
        self.my_frame.pack(fill="both", expand=True)

if __name__ == "__main__":
  app = App()
  app.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM