考虑到这个问题的接受答案:
Using buttons in Tkinter to navigate to different pages of the application?
有没有办法扩展Page类,以便可以从MainView初始化任意数量的页面,而不必为每个单独的页面创建一个新类?
谢谢!
答案 0 :(得分:0)
该示例的重点是展示如何在不同页面之间切换。我没有完全看到有多个完全相同的页面。
话虽如此,没有什么可以阻止您根据需要创建单个页面的实例。这里对您链接的答案略有修改,这会创建十个相同的页面并让您在它们之间循环:
import Tkinter as tk
class Page(tk.Frame):
def __init__(self, title):
tk.Frame.__init__(self, bd=1, relief="sunken")
self.label = tk.Label(self, text=title)
self.label.pack(side="top", fill="both", expand=True)
def show(self):
self.lift()
class MainView(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
buttonframe = tk.Frame(self)
container = tk.Frame(self)
buttonframe.pack(side="top", fill="x", expand=False)
container.pack(side="top", fill="both", expand=True, padx=2, pady=2)
next_button = tk.Button(buttonframe, text=" > ", command=self.next_page)
prev_button = tk.Button(buttonframe, text=" < ", command=self.prev_page)
prev_button.pack(side="left")
next_button.pack(side="left")
self.pages = []
for i in range(10):
page = Page(title="page %d" % i)
page.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
self.pages.append(page)
self.pages[0].show()
def next_page(self):
# move the first page to the end of the list,
# then show the first page in the list
page = self.pages.pop(0)
self.pages.append(page)
self.pages[0].show()
def prev_page(self):
# move the last page in the list to the front of the list,
# then show the first page in the list.
page = self.pages.pop(-1)
self.pages.insert(0, page)
self.pages[0].show()
if __name__ == "__main__":
root = tk.Tk()
main = MainView(root)
main.pack(side="top", fill="both", expand=True)
root.wm_geometry("400x400")
root.mainloop()