我遇到的问题专门与 Label 小部件有关。在链接的代码中,Text 小部件和 Button 小部件的测试都获取继承的值并正确显示它。
您可以在PageTwo 类中找到有问题的标签小部件
我试图在标签中继承和显示的变量是第一类中设置的“ num ”变量。
目标是获取该变量,在另一个类中设置值,然后稍后在 Label 小部件中显示新设置的值。
我试图设置 Label 以在 f 字符串中直接显示变量作为 str 值,以及在 PageTwo 中设置局部变量以获取 TestClass.num 的值
有问题的代码示例是:
import tkinter as tk
class TestClass(tk.Tk):
num = None
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Game")
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 (PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(PageOne)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self,
text="Make a selection",
wraplength=450, justify='center')
label.pack(padx=10, pady=10)
TestClass.num = tk.StringVar()
tk.Radiobutton(self, text="1", variable=TestClass.num, value="1", ).pack()
tk.Radiobutton(self, text="2", variable=TestClass.num, value="2", ).pack()
tk.Radiobutton(self, text="3", variable=TestClass.num, value="3", ).pack()
view_selection = tk.Button(self, text="test selection", command=lambda: print(TestClass.num.get()))
view_selection.pack()
next_page = tk.Button(self, text="Next Page",
command=lambda: controller.show_frame(PageTwo))
next_page.pack(pady=10, padx=10)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# label = tk.Label(self, text=TestClass.num.get()
label = tk.Label(self, text=f"The number should show up here -> {TestClass.num.get()} <- ")
label.pack()
text1 = tk.Text(self)
text1.pack()
see_num = tk.Button(self, text="View Number",
command=lambda: text1.insert('1.0', TestClass.num.get()))
see_num.pack(pady=10, padx=10)
app = TestClass()
app.mainloop()