2016-08-10 223 views
0

我在python 3.4中使用Tkinter來創建一個基於文本的遊戲,我無法弄清楚如何從Entry小部件獲取字符串,它只是返回Py_Var#,#是一個數字。我已經看過類似問題的答案,但他們中沒有一個與我所需要的和所擁有的完全一致。這是相關的代碼段:Python Tkinter StringVar只顯示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和它的閱讀奇怪,但瓦特/ e。

回答

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中,註釋用#符號創建。所以我將*更改爲#

+0

嗚呼!謝謝Parviz,知道了。在我遇到的每個地方,都有着與衆不同的答案,這與衆不同,非常感謝。 –

+0

不客氣! –

2

你在SubmitName()有兩個錯誤。

首先,你需要獲取文本是這樣的:

txt = playername.get() 

然後,你需要打印txt

print(txt) 

搞錯了,你打印的StringVar變量本身。