我有一个返回用户输入的函数。但是,我不能在句子中使用该用户输入。经过前几条评论后,我意识到这可能是因为在用户输入任何值之前创建了标签。
我不确定如何解决此问题。任何帮助将不胜感激。
class NamePage(tk.Frame):
def __init__(self, parent, controller):
self.controller = controller
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Please type the
name you want your character to have",
width=127, height=30,
font=font_remaining, bd=1,
relief="solid", anchor=CENTER)
label.grid(row=1, column=1, pady=10, padx=10)
button_continue = tk.Button(self, width=40, height=3, bd=1
relief="solid",
font=font_button, text="Continue",
command=lambda: value())
button_continue.place(x=425, y=500)
entry1 = tk.Entry(self,
textvariable=self.controller.shared_data["name"])
entry1.place(x=425, y=400)
entry1.config(width=67)
def value():
value1 = self.controller.shared_data["name"].get()
print(value1)
controller.show_frame(TitlePage)
class TitlePage(tk.Frame):
def __init__(self, parent, controller):
self.controller = controller
tk.Frame.__init__(self, parent)
label = tk.Label(self, bg=background_options, text="The Adventure of
"
+
self.value_name(), width=127, height=30,
font=font_title, bd=1,
relief="solid", anchor=CENTER)
label.grid(row=1, column=1, pady=10, padx=10)
def value_name(self):
value2 = self.controller.shared_data["name"].get()
input_name = value2
print(input_name)
return input_name
app = firstwindow()
app.mainloop()
用户输入John
预期结果=约翰历险记
实际结果=冒险
答案 0 :(得分:0)
最简单的解决方法是在StringVar
中为标签创建一个TitlePage
。然后,当您在初始输入后切换帧时,直接设置新标签:
class NamePage(tk.Frame):
def __init__(self, parent, controller):
...
def value():
value1 = self.controller.shared_data["name"].get()
controller.frames[TitlePage].var.set(f"The Adventure of {value1}") #set new value here
controller.show_frame(TitlePage)
class TitlePage(tk.Frame):
def __init__(self, parent, controller):
self.controller = controller
tk.Frame.__init__(self, parent)
self.var = StringVar() #create StringVar here
label = tk.Label(self, bg=background_options, textvariable=self.var, #assign textvariable
width=127, height=30, font=font_title, bd=1,
relief="solid", anchor=CENTER)
...