简体   繁体   中英

Is there a way to change a global value from inside a function?

I am currently working an a snake game, but I first want a settings window to show up.i used tkinter for this. In smaller projekts I just wrote all of the code into the pressButton function, but I want to have non spagetti code now, so im not going with that. The problem is, that I have no idea how to get the entered values in the entry brackets into my main code, as global variables, out of the pressButton function and the settingsWin function. The problem is that I use the function as a command for the Button, so I cannt use "return". Can you change global variables in the main code direcktly from inside of a function? If yes how? Or is there another way to solve this? My Code:

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"

It is often indicative of code smell to require that a function alter variables at scopes outside the function (except possibly in the case of closures, which are quite useful), it is possible to do so using the global keyword:

greeting = "Hello world!"

def greet():
    global greeting
    greeting = "Goodbye world!"

print(greeting)

greet()

print(greeting)

By declaring the variable greeting to be of global scope, altering the variable within the function definition allows the function to affect the global variable.

If you are working within nested subs, the nonlocal keyword will provide access within the inner sub, to the variable in the outer sub. It works similar to global , except that it is for broader lexical scope, not global scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM