Làm cho mỗi trang trở thành một khung. Sau đó, tất cả các nút của bạn cần làm là ẩn mọi thứ hiển thị, sau đó hiển thị khung mong muốn.
Một phương pháp đơn giản để thực hiện việc này là xếp các khung lên nhau (đây là một lần khi place
có ý nghĩa) và sau đó, lift()
khung bạn muốn hiển thị. Kỹ thuật này hoạt động tốt nhất khi tất cả các trang có cùng kích thước; trong thực tế, nó đòi hỏi bạn phải thiết lập một cách rõ ràng kích thước của khung chứa.
Sau đây là ví dụ được tạo ra. Đây không phải là cách duy nhất để giải quyết vấn đề, chỉ bằng chứng rằng nó không phải là một vấn đề đặc biệt khó giải quyết:
import Tkinter as tk
class Page(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
def show(self):
self.lift()
class Page1(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
label = tk.Label(self, text="This is page 1")
label.pack(side="top", fill="both", expand=True)
class Page2(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
label = tk.Label(self, text="This is page 2")
label.pack(side="top", fill="both", expand=True)
class Page3(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
label = tk.Label(self, text="This is page 3")
label.pack(side="top", fill="both", expand=True)
class MainView(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
p1 = Page1(self)
p2 = Page2(self)
p3 = Page3(self)
buttonframe = tk.Frame(self)
container = tk.Frame(self)
buttonframe.pack(side="top", fill="x", expand=False)
container.pack(side="top", fill="both", expand=True)
p1.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p2.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p3.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
b1 = tk.Button(buttonframe, text="Page 1", command=p1.lift)
b2 = tk.Button(buttonframe, text="Page 2", command=p2.lift)
b3 = tk.Button(buttonframe, text="Page 3", command=p3.lift)
b1.pack(side="left")
b2.pack(side="left")
b3.pack(side="left")
p1.show()
if __name__ == "__main__":
root = tk.Tk()
main = MainView(root)
main.pack(side="top", fill="both", expand=True)
root.wm_geometry("400x400")
root.mainloop()
hơn bạn rất nhiều, chính xác những gì tôi đã làm sau! –
@CasparWylie: Tất cả ví dụ này có nghĩa là toàn bộ ví dụ này là một khối văn bản. Bạn có thể chia nó thành bao nhiêu tệp tùy thích - điều đó không liên quan gì đến giải pháp. Mỗi "trang" có thể dễ dàng là mô-đun riêng của nó. –
@BryanOakley, sẽ không tốt hơn khi sử dụng sổ ghi chép cho những thứ như thế này? http://www.tkdocs.com/tutorial/complex.html#notebook – user3885927