Tkinter小部件都包装在同一框架中

时间:2019-05-20 20:22:23

标签: python python-3.x tkinter tk

我正在尝试制作带有多个窗口的相当简单的GUI。我现在将我的窗口构建为类,现在每个窗口中都带有一个标签。我似乎无法弄清楚为什么当我运行程序时,它将所有标签都包装在“ StartPage”上,而其他所有窗口中都没有。可能是我的班级配置不正确?

import tkinter as tk


class application(tk.Tk):

def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, **kwargs)
    container = tk.Frame(self)
    container.pack(side = 'top', fill = 'both', expand = True)

    container.grid_rowconfigure(0, weight = 1)
    container.grid_columnconfigure(0, weight = 1)

    self.frames = {}

    for F in (StartPage, WeeklyBudget, LongtermSavings, Investments):
        frame = F(container, self)
        self.frames[F] = frame

        frame.grid(row=0, column=0, sticky="nsew")


    self.ShowFrame(StartPage)

def ShowFrame(self, cont):
    frame = self.frames[cont]
    frame.tkraise()


class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        start_label = tk.Label(self, text = 'Welcome to Finance Track!')
        start_label.pack()
        week_btn = tk.Button(self, text = 'Weekly Budgeting', command =lambda: controller.ShowFrame(WeeklyBudget))
    savings_btn = tk.Button(self, text = 'Longterm Savings', command = lambda: controller.ShowFrame(LongtermSavings))
    invest_btn = tk.Button(self, text = 'Investments', command = lambda: controller.ShowFrame(Investments))


    week_btn.pack(pady = 10, padx = 10)
    savings_btn.pack(pady = 10, padx = 10)
    invest_btn.pack(pady = 10, padx = 10)

class WeeklyBudget(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(text = 'Welcome to your Weekly Budget')
        label.pack()
        add_btn = tk.Button(text = 'add new week')
        add_btn.pack()

class LongtermSavings(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(text = 'Welcome to your Longterm Savings')

        label.pack()

class Investments(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(text = 'Welcome to your Investments')
        label.pack()

app = application()
app.mainloop()

正如我之前所描述的,当前结果只是一个窗口,其中包含所有标签和所有按钮。

1 个答案:

答案 0 :(得分:2)

正如jasonharper所提到的,您并没有定义许多小部件的父级(又称母版)。

class Investments(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(text = 'Welcome to your Investments')
        label.pack()

例如,使用这个Investments类,默认情况下,标签将以其父窗口的形式显示在窗口中,将其父窗口设置为新创建的框架,只需执行以下操作:

class Investments(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text = 'Welcome to your Investments')
        label.pack()