我目前正在使用Tkinter进行一个项目,我希望在StartPage中使用按钮文本将我带到PageOne,并将按钮文本作为标签。
我尝试创建一个可更改全局变量并让PageOne访问该全局变量的函数,但由于MiniProject类仅运行一次,所以它似乎不起作用。
因此,我尝试将Tkinter字符串变量与PageOne标签相关联,但是我不确定如何执行此操作。如何将两个课程链接在一起?还是应该将PageOne作为功能放在StartPage下?
请告知。
#code layout from https://pythonprogramming.net/change-show-new-frame-tkinter/
import tkinter as tk
class MiniProject(tk.Tk): #baseline code for adding/switching pages
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, *kwargs)
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):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame): #Front page with buttons A-D
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
for letter in ["A","B","C","D"]: #clicking button should bring me to PageOne with label as button text
button = tk.Button(self, text = letter, command = lambda j = letter:\
[PageOne.changename(j),controller.show_frame(PageOne)])
button.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
my_string_var = tk.StringVar()
my_string_var.set("Default Text")
label = tk.Label(self, textvariable = my_string_var) #Supposed to display button number
label.pack(pady=10,padx=10)
button1 = tk.Button(self, text = "TO HOME", command = lambda: controller.show_frame(StartPage))
button1.pack()
def changename(name):
my_string_var.set(name)
app = MiniProject()
app.mainloop()
接收回溯
Exception in Tkinter callback
Traceback (most recent call last):
File "/Users/kohtziyong/anaconda3/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "<ipython-input-3-3405dd392652>", line 37, in <lambda>
[PageOne.changename(j),controller.show_frame(PageOne)])
File "<ipython-input-3-3405dd392652>", line 52, in changename
my_string_var.set(name)
NameError: name 'my_string_var' is not defined