【发布时间】:2016-03-21 22:57:18
【问题描述】:
我正在尝试自学如何使用 tkinter,但我通过 youtube 找到了一个我并不完全理解的有用代码。如果有人可以帮助我理解它,将不胜感激。用# ... **标记了我不明白的地方。
import tkinter as tk # why not from tkinter import? **
class SampleApp(tk.Tk): # why tk.TK **
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
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, PageOne, PageTwo):
page_name = F.__name__
frame = F(container, self) # **
self.frames[page_name] = frame # **
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise() # **
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent) # **
self.controller = controller # **
label = tk.Label(self, text="This is the start page",
font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
【问题讨论】:
-
能否分享一下 youtube 链接?
-
@BryanOakley 如果您还在寻找,我已经看到 this 教程使用来自 original question 的代码,尽管他确实说明了它的来源。还有this。
-
@double_j:是的,我很久以前就找到了,但是谢谢。我没有看到您提供的其他链接。我改进了原始答案,因此我可以知道谁开始使用我的代码以及谁开始使用该视频教程。该代码已经有了自己的生命,它出现在很多新手问题中。
标签: python-3.x tkinter