Python Tkinter 框架

Python Tkinter Frames

为什么我的程序没有像标签那样改变框架?

我的登录页面检查用户和密码正确,但我不知道如何在验证后切换到主程序。

import tkinter as tk
from tkinter import ttk
import dbm

class Program(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 = {}
        Frames = (LoginPage, StartPage)
        for F in Frames:
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column = 0, sticky="nsew")

        self.ShowF(LoginPage)

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

class LoginPage(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)
        stats = tk.Label(self, text = 'Insira os dados para a validação')
        stats.pack()
        lab = tk.Label(self, text = ('Usuário'))
        lab.pack()
        self.ent = tk.Entry(self)
        self.ent.pack()
        lab2 = tk.Label(self, text = ('Senha'))
        lab2.pack()
        self.ent2 = tk.Entry(self, show='*')
        self.ent2.pack()
        but = tk.Button(self, text = 'Validar', command = self.Validacao)
        but.pack()
        self.lab3 = tk.Label(self, text = '')
        self.lab3.pack()

    def Validacao(self):
        user = self.ent.get()
        passw = self.ent2.get()
        with dbm.open('files/contas','rb') as contas:
            accv = [key1.decode() for key1 in contas.keys()]
            passv = [contas[key].decode() for key in contas.keys()]
            while True:
                try:
                    k = accv.index(user)
                    k1 = passv.index(passw)
                    break
                except:
                    self.lab3['text'] = ('Usuário e/ou senha inválidos!')
                    return
            if k == k1:
                self.lab3['text'] = ('Validação concluída!')
                lambda :controller.ShowF(StartPage) #The problem is here(I think)

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Start Page")
        label.pack(pady=10, padx=10)

        button = tk.Button(self, text="Button1")
        button.pack()
        buttona = tk.Button(self, text="Button2")
        buttona.pack()

app = Program()
app.mainloop()

lambda :controller.ShowF(StartPage)不调用函数,它returns调用函数的新函数。您需要删除 lambda:

self.controller.ShowF(StartPage)

此外,您的代码需要保存对 controller:

的引用
class LoginPage(tk.Frame):
    def __init__(self,parent,controller):
        self.controller = controller
        ...

创建 var 时问题已解决: self.var = lambda: controller.ShowF(起始页) 然后更改按钮文本和按钮['command'] = self.var