【问题标题】:Is there a way to change a global value from inside a function?有没有办法从函数内部更改全局值?
【发布时间】:2020-10-11 20:47:33
【问题描述】:

我目前正在玩蛇游戏,但我首先希望显示一个设置窗口。我为此使用了 tkinter。在较小的项目中,我只是将所有代码都写到了 pressButton 函数中,但是我现在想要非意大利面条代码,所以我不这样做。问题是,我不知道如何将输入括号中的输入值作为全局变量从 pressButton 函数和 settingsWin 函数中获取到我的主代码中。问题是我将该函数用作按钮的命令,所以我不能使用“return”。您可以直接从函数内部更改主代码中的全局变量吗?如果是怎么办?还是有其他方法可以解决这个问题? 我的代码:

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"

【问题讨论】:

标签: python button tkinter command tk


【解决方案1】:

要求函数更改函数范围内的变量通常表明代码有异味(可能在闭包的情况下非常有用),可以使用 global 关键字来做到这一点:

greeting = "Hello world!"

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

print(greeting)

greet()

print(greeting)

通过将变量 greeting 声明为全局范围,在函数定义中更改变量允许函数影响全局变量。

如果您在嵌套的 subs 中工作,nonlocal 关键字将在内部 sub 内提供对外部 sub 中的变量的访问。它的工作方式类似于global,只是它适用于更广泛的词法范围,而不是全局范围。

【讨论】:

  • 谢谢,这正是我想要的 :)
猜你喜欢
  • 1970-01-01
  • 2013-03-14
  • 2021-03-12
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多