当用户点击“登录”按钮时,我正试图将“搜索”框架提升到“登录”框架之上。我认为这可能与我如何堆叠我的帧有关,但不确定它到底是什么。
我测试了show_frame函数是否在用户单击“登录”按钮后运行,它确实运行了,但框架没有被解除。
import tkinter as tk
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
root = tk.Frame(self)
self.screen_w = root.winfo_screenwidth()
self.screen_h = root.winfo_screenheight()
self.frames = {}
for F in (Login, Search):
page_name = F.__name__
frame = F(parent=root, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("Search")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class Login(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.screen_w = controller.screen_w
self.screen_h = controller.screen_h
self.display()
def display(self):
#login page (frame)
self.login_page = tk.Frame(width=self.screen_w, height=self.screen_h, background="#ABEBC6")
self.login_section = tk.Frame(width=100, height=100, background="#52BE80")
self.login_page.pack()
self.login_section.place(in_=self.login_page, anchor="c", relx = 0.5, rely = 0.5, relheight = 0.5, relwidth = 0.5)
self.login_button = tk.Button(self.login_section, text='Login', fg = 'black', bg = 'green')
self.login_button.place(relx = 0.5, rely = 0.55, relheight = 0.1, relwidth = 0.4, anchor = 'c')
self.login_button.bind('<Button-1>', self.check_login)
def check_login(self, event):
self.controller.show_frame('Search')
class Search(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.screen_w = controller.screen_w
self.screen_h = controller.screen_h
self.display()
def display(self):
#search page (frame)
self.search_page = tk.Frame(width=self.screen_w, height=self.screen_h, background="#85C1E9")
self.search_section = tk.Frame(width=100, height=100, background="#5DADE2")
self.search_page.pack()
self.search_section.place(in_=self.search_page, relx = 0.5, rely = 0.5, relheight = 0.5, relwidth = 0.5, anchor = 'center')
if __name__ == "__main__":
app = App()
app.mainloop()发布于 2019-10-24 06:25:04
问题的根源在于,您将内部框架放在根窗口而不是页面中。
您需要更改以下内容:
self.login_page = tk.Frame(width=self.screen_w, height=self.screen_h, background="#ABEBC6")
self.login_section = tk.Frame(width=100, height=100, background="#52BE80")..。(调用Frame时请注意self参数):
self.login_page = tk.Frame(self, width=self.screen_w, height=self.screen_h, background="#ABEBC6")
self.login_section = tk.Frame(self, width=100, height=100, background="#52BE80")..。同样,对于搜索页面也是如此
这带来了许多其他问题,但这是根本问题。您在每个“页面”中创建的每个小部件都需要位于该“页面”的框架内。
另一个问题是,您在主窗口中创建了一个名为root的框架,并将其他所有内容都放在了root中。但是,您永远不会在root上调用pack、place或grid。正因为如此,你的小部件都不会出现。
对这个问题最简单的解决方案是对它调用pack:
root.pack(fill="both", expand=True)您还会在启动时显示“搜索”页面,而不是登录页面,因此登录按钮永远不会出现。
您需要在__init__中调用self.show_frame("Login")而不是self.show_frame("Search")。
https://stackoverflow.com/questions/58531579
复制相似问题