Python Tkinter StringVar仅显示Py_Var(数字)



我在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()

此外,第一次使用stackerflow和它的阅读怪异,但w/e。

您在SubmitName()中有两个错误。

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

txt = playername.get()

然后你需要打印txt:

print(txt)

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

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()

我更改的内容:
-删除CCD_ 5。我们其实并不需要它
-函数内部更改:将playername.get更改为playername = entry1.get()
-添加了frame3.grid()(没有几何管理,窗口小部件无法在屏幕上显示(
-还有一点编辑:在Python中,注释是用#符号创建的。所以我把*改成了#

我很高兴在这里找到一个解决方案,但所有这些"原样"的答案都不适用于我的设置,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()

相关内容

  • 没有找到相关文章

最新更新