我尝试创建一个用户界面,用户在输入框中输入自己的名字,当我尝试打印名称变量时,PY_VAR被打印出了问题。
import tkinter as tk
class TestApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.geometry('400x500')
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.grid()
def save(self,var1name):
print(var1name)
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
var1name = tk.StringVar()
#Entry of basic information
tk.Label(self, text="Please enter setup").grid(row=0, column=1, sticky="W")
tk.LabelFrame(self, text="labelframe").grid()
tk.Label(self, text="Name: ").grid(row=1, column=0, sticky="W")
tk.Entry(self,textvar=var1name).grid(row=1, column=2, sticky="W")
tk.Button(self, text="Set",
command=lambda: master.save(var1name)).grid(row=9, column=1, sticky="E")
#tk.Button(self, text="Next",
#command=lambda: master.switch_frame(PageOne)).grid(row=9, column=2, sticky="E")
if __name__ == "__main__":
app = TestApp()
app.mainloop()
我希望在Python界面上打印一个名称,但改为打印PY_VAR
答案 0 :(得分:2)
var1name是对Tkinter.StringVar对象的引用。您需要调用其 get方法来访问其表示的值,例如:
print (var1name.get())
get 方法以Python的形式返回变量的当前值。 对象。
在您的代码中:
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
var1name = tk.StringVar()
# Entry of basic information
tk.Label(self, text="Please enter setup").grid(row=0, column=1, sticky="W")
tk.LabelFrame(self, text="labelframe").grid()
tk.Label(self, text="Name: ").grid(row=1, column=0, sticky="W")
tk.Entry(self, textvar=var1name).grid(row=1, column=2, sticky="W")
tk.Button(self, text="Set",
command=lambda: master.save(var1name.get())).grid(row=9, column=1, sticky="E")