【发布时间】:2020-07-24 16:17:08
【问题描述】:
我正在尝试使用 tkinter 创建一个简单的 Python 3.x GUI 项目,只是为了更好地学习该语言(我不久前开始学习 Python),其中唯一的作用就是在不同页面之间切换为按钮被点击。问题是对象没有进入屏幕中心。我的代码有什么问题?
图片:
import tkinter as tk
LARGE_FONT = ("verdana", 10)
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.grid()
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="snew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage (tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label1 = tk.Label(self, text="Start Page", font=LARGE_FONT)
label1.grid(row=0, column=0)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame(PageOne))
button1.grid(row=1, column=0)
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.grid(row=2, column=0)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label2 = tk.Label(self, text="Page One", font=LARGE_FONT)
label2.grid(row=0, column=0, sticky="E")
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.grid(row=1, column=0)
button3 = tk.Button(self, text="Go to Start Page",
command=lambda: controller.show_frame(StartPage))
button3.grid(row=2, column=0)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label2 = tk.Label(self, text="Page Two", font=LARGE_FONT)
label2.grid(row=0, column=0,sticky="E")
button2 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame(PageOne))
button2.grid(row=1, column=0)
button3 = tk.Button(self, text="Go to Start Page",
command=lambda: controller.show_frame(StartPage))
button3.grid(row=2, column=0)
app = Application()
app.title("Application")
app.mainloop()
【问题讨论】:
-
你从一个太复杂的例子开始。我建议您首先创建一个只有一个页面的程序。在您尝试同时处理多个页面之前,先让它发挥作用。
-
感谢您的回复!实际上,我之前已经做了一些简单的项目,只有一页,我觉得准备好尝试一些更难的东西了。我了解 OOP 和 tkinter 的基础知识,所以我开始了我在 youtube 教程中看到的这个新项目,但我仍然无法解决中心化问题,真的很难解决吗?
标签: python-3.x oop user-interface tkinter