我是Python新手,试图理解下面的代码。此代码应创建3个框架对象,这些对象可以旋转到前面以交换页面。
APP类应该创建这3个新对象。我不确定是不是。
我尝试的是通过Dashboard类中的函数修改该类上的标签。
i、 e.Dashboard.update()
有人能解释一下APP类是如何为3个窗口创建框架对象的吗。我现在确定它是,我想我正在尝试更新类中的文本,而不是该类的对象
### Import libaries
import requests
import pyodbc
import tkinter as tk
from tkinter import *
from tkinter import messagebox, ttk
### Set global fonts
TITLE_FONT = ("Verdana", 12)
### Define the applicaiton class
class APP (Frame):
### Build the init function to create the container and windows
def __init__ (self, master=None ):
Frame.__init__(self, master)
self.grid()
# Set the application window title
self.master.title("Playing Around with Classes")
# set the size of the row height for the application
self.master.rowconfigure(0, weight=1)
self.master.rowconfigure(1, weight=35)
self.master.rowconfigure(2, weight=1)
self.master.rowconfigure(3, weight=1)
#Row 0 - Title area
label = tk.Label(master, text="Playing Around with Classes", font=TITLE_FONT)
label.grid(row=0, columnspan=3, sticky="nsew")
# Main presentation are
Frame2 = Frame(master, bg="#263D42")
Frame2.grid(row = 1, column = 0, rowspan = 1, columnspan = 3, sticky = "nsew")
# List of pages
self.frames = {}
# i think this loop defines the class objects
for F in (NetworkMap,AuthorPage,Dashboard):
frame = F(Frame2, self)
self.frames[F] = frame
frame.grid(row=0, column=1, sticky="nsew")
self.show_frame(Dashboard)
### Define the show_frame function that will bring the selected fram to the front so it can be viewed
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
### Create a class for the Dashboard page. This will also be the start page when the application starts
class Dashboard (tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent, bg="#263D42")
label = tk.Label(self, text="Text to change", font=TITLE_FONT, bg="#263D42", fg="white", pady = 20)
label.grid(row=0, column=0, sticky="nsew")
def update(self):
self.allPapersLabel.config(text="Changed Text")
### Create a page to get the Author detasil
class AuthorPage (tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="Get Author", font=TITLE_FONT)
label.grid(row=0, column=0, sticky="nsew")
class NetworkMap (tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="Network Map", font=TITLE_FONT)
label.grid(row=0, column=0, sticky="nsew")
def changeText():
Dashboard.update()
changeText()
root = tk.Tk()
root.geometry("600x800+100+100")
app = APP(master=root)
app.mainloop()
关键在于:
请记住
NetworkMap
、AuthorPage
和Dashboard
是类。类是可调用的,用作特定类型的新实例的工厂因此,基本上for循环使
F
成为每个类的别名(或标签),并依次调用它们来实例化对象请记住,在大多数语言中我们所称的“变量”在Python中被称为名称。从语言手册:
所以
F
只不过是一个方便的标签,用于引用这三个类。for循环头将名称绑定到类顺便说一句:这看起来像是一个^{} 的重新实现。我建议用它来代替
编辑
帧被保存到
frames
字典App
对象中。因此,在App
实例的所有方法中,您都可以访问self.frames
以获得各个帧有点奇怪(至少对我来说)的是,框架的类对象被用作从字典中进行选择的键
因此,在
App
的方法中使用self.frames[AuthorPage]
应该返回AuthorPage
帧相关问题 更多 >
编程相关推荐