[英]Best way to change value of global value inside a function in Python?
[英]Is there a way to change a global value from inside a function?
我目前正在做一個蛇游戲,但我首先想要一個設置窗口顯示出來。我為此使用了 tkinter。 在較小的項目中,我只是將所有代碼都寫入了 pressButton 函數,但我現在想要非意大利面條代碼,所以我不打算這樣做。 問題是,我不知道如何將輸入括號中的輸入值作為全局變量從 pressButton 函數和 settingsWin 函數中獲取到我的主代碼中。 問題是我使用該函數作為按鈕的命令,所以我不能使用“返回”。 您可以從函數內部直接更改主代碼中的全局變量嗎? 如果是如何? 或者有其他方法可以解決這個問題嗎? 我的代碼:
def settingsWin():
def pressButton():
len = entryLen.get()
wid = entryWid.get()
speed = entrySpeed.get()
print(len+wid+speed)
SettingsWin.destroy()
return len
SettingsWin = Tk()
SettingsWin.geometry("600x600")
SettingsWin.title("Settings")
label1 = Label(SettingsWin, text="playing field [tiles]")
label1.pack()
entryLen = Entry(SettingsWin, bd=2, width=20)
entryLen.pack()
label2 = Label(SettingsWin, text="X")
label2.pack()
entryWid = Entry(SettingsWin, bd=2, width=20)
entryWid.pack()
labelblanc = Label(SettingsWin, text="")
labelblanc.pack()
label3 = Label(SettingsWin, text="Speed [ms per tick]")
label3.pack()
entrySpeed = Entry(SettingsWin, bd=2, width="20")
entrySpeed.pack()
okButton = Button(SettingsWin, text="OK", command=pressButton)
okButton.pack()
SettingsWin.mainloop()
len = "len"
wid = "wid"
speed = "speed"
要求函數在函數外的范圍內改變變量通常是代碼異味的表現(除非可能在閉包的情況下,這非常有用),可以使用global
關鍵字來做到這一點:
greeting = "Hello world!"
def greet():
global greeting
greeting = "Goodbye world!"
print(greeting)
greet()
print(greeting)
通過將變量greeting
聲明為全局作用域,改變函數定義中的變量允許函數影響全局變量。
如果您在嵌套子程序中工作,則nonlocal
關鍵字將提供內部子程序中對外部子程序中變量的訪問。 它的工作原理類似於global
,但它適用於更廣泛的詞法范圍,而不是全局范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.