Python Tkinter StringVar只显示Py_Var(数字)

时间:2016-08-10 05:34:42

标签: python tkinter tkinter-entry

我在python 3.4中使用Tkinter制作基于文本的游戏,我无法弄清楚如何从Entry小部件中获取字符串,它只返回Py_Var#,#是一个数字。我已经查看了类似问题的答案,但是没有一个能够与我需要的东西完全一致。这是相关的代码片段:

from tkinter import * 

win = Tk() 
win.geometry("787x600")

playername = StringVar()

def SubmitName():
    playername.get
    #messagebox.showinfo("Success", playername)
    print(playername)

frame3 = Frame(win) 
frame3.pack()
label1 = Label(frame3, text="You awaken in a room, with no memories of yourself or your past. ")

label2 = Label(frame3, text="First, how about you give yourself a name:")

label1.config(font=("Courier", 11)) 
label2.config(font=("Courier", 11))

entry1 = Entry(frame3, textvariable=playername) 
entry1.config(font=("Courier", 11))

label1.grid(row=0, column=0, columnspan=3) 
label2.grid(row=1, column=0)

entry1.grid(row=1, column=1)

bnamesub= Button(frame3, text="Submit", command=lambda: SubmitName()) 
bnamesub.grid()

win.mainloop()

此外,第一次使用stackoverflow及其读取很奇怪,但没有。

3 个答案:

答案 0 :(得分:2)

SubmitName()中有两个错误。

首先,你需要得到这样的文字:

txt = playername.get()

然后您需要打印txt

print(txt)

您错误地打印了StringVar变量本身。

答案 1 :(得分:0)

from tkinter import *
import pickle

win = Tk()
win.geometry("787x600")

def SubmitName():
        playername = entry1.get()
        messagebox.showinfo("Success", playername)
        print(playername)

frame3 = Frame(win)
frame3.grid()
label1 = Label(frame3, text="You awaken in a room, with no memories of yourself or your past. ")

label2 = Label(frame3, text="First, how about you give yourself a name:")

label1.config(font=("Courier", 11))
label2.config(font=("Courier", 11))

#name entered is a StringVar, returns as Py_Var7, but I need it to return the   name typed into entry1.
entry1 = Entry(frame3)
entry1.config(font=("Courier", 11))

label1.grid(row=0, column=0, columnspan=3)
label2.grid(row=1, column=0)

entry1.grid(row=1, column=1)

bnamesub= Button(frame3, text="Submit", command=lambda: SubmitName())
bnamesub.grid()

我改变了什么:
-deleted playername = StringVar()。我们真的不需要它;
- 在函数内部更改:将playername.get更改为playername = entry1.get();
-added frame3.grid()(没有几何管理,小部件无法在屏幕上显示。);
- 另外,一点点编辑:在Python中,使用#符号创建注释。所以我将*更改为#

答案 2 :(得分:0)

我很高兴在这里找到一个解决方案,但所有这些“按原样”的答案均不适用于我的设置python3.8,pycharm 2018.2 因此,如果任何人都可以回答这个问题,看来entry1.get()不能用作字符串。我首先想将其添加到列表中,然后我做了一个更简单的版本来指出问题所在:

from tkinter import *
import pickle

win = Tk()
win.geometry("300x300")
#playername = StringVar()

def SubmitName():
    labell = Label(win, text="Little tryup").grid()
    playername = entry1.get()
    # result about line 11: 'NoneType' object has no attribute 'get'
    labelle = Label(win, text=playername).grid()
#    print(txt)

label1 = Label(win, text="Enter a name:").grid()
entry1 = Entry(win).grid()
boutonne = Button(win, text="label-it!", command=lambda: SubmitName())
boutonne.grid()
win.mainloop()