2014-10-03 24 views
-3

我目前正在寫一個掛人遊戲。使用Tkinter進行GUI。Python - 如何獲取函數中的字符串?

如何從一個函數得到一個字符串:

def startgame(): 
    player21abel=Label(text=" Guess a Letter  ",fg="black").place(x=10,y=60) 
    mbutton=Button(text=" Press to summit ",command=guess).place(x=220,y=100) 
    player2=StringVar() 
    player2input=Entry(textvariable=player2).place(x=220,y=56) 
    test="" 
    uetext=utext.get() 


def guess(): 
    test=player2.get() 
    test="" 
    player2=StringVar 
    print (test) 

我得到的錯誤:

line 16, in guess
test=player2.get()
UnboundLocalError: local variable 'player2' referenced before assignment

我想從player2input並處理它的函數猜測的文本框中輸入。但它不認爲它是一個字符串?

回答

0

player2不存在guess命名空間。在函數之間共享數據的典型方法是使用一類:

class App(object): 
    def __init__(self): 
     self.master = Tk() 
    def startgame(): 
     player21abel=Label(self.master, text=" Guess a Letter  ",fg="black") 
     player2label.place(x=10,y=60) 
     mbutton=Button(self.master, text=" Press to summit ",command=self.guess) 
     mbutton.place(x=220,y=100) 
     self.player2=StringVar() 
     player2input=Entry(self.master, textvariable=self.player2) 
     player2input.place(x=220,y=56) 
     test="" 
     uetext=utext.get() 


    def guess(): 
     test=self.player2.get() 
     test="" 
     self.player2=StringVar 
     print (test) 

然後,你與它的工作方式如下:

app = App() 
app.startgame() 

請注意,您有一些其他錯誤,以及 - - 您沒有將父窗口小部件傳遞給您的標籤/條目/按鈕,您通常應該製作一個窗口小部件,然後在單獨的行中使用它的幾何管理器。否則你的參考將全部爲None。例如

foo = button(master, ...).grid(...) # Wrong: foo is None!!! 

foo = button(master, ...) 
foo.grid(...) # right, foo is a tkinter Widget. 
+0

對不起。我不明白你的意思是使用這些命令: – Angus 2014-10-04 09:40:56

+0

app = App() app.startgame()。在即將出現的代碼中,如果我想要一個按鈕進入某個函數,是否需要替換:mbutton = Button(text =「Press to start game」,command = startgame).place(x = 123,y = 100) – Angus 2014-10-04 09:41:47

0

您必須將它作爲參數傳遞給函數。

爲此在tkinter看看這個答案:https://stackoverflow.com/a/6921225/1165441

所有你需要做的是使用你想要的參數調用你的功能一個lambda。

您將需要重新安排你的代碼位,但該命令屬性將是這樣的:

command=lambda: guess(paramYouWantToPass) 

編輯:我要說的是,張貼@mgilson答案是解決比較正確的做法您問題,但瞭解如何使用lambdas將參數傳遞給tkinter命令回調,您應該理解這一點。

相關問題