用tkin中的按钮更改变量

2024-05-20 20:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

问题所在的代码相当大,所以我在这里起草一个手绘版本。在

import tkinter

variable = "data"

def changeVariable():
    variable = "different data"

def printVariable():
    print(variable)

window = tkinter.Tk
button1 = tkinter.Button(window, command=changeVariable)
button1.pack()
button2 = tkinter.Button(window, command=printVariable)
button2.pack()

所以在这个例子中,我按第一个按钮来更改“variable”,然后按第二个按钮打印它。而不是“打印数据”。我搜索了一下,决定在主代码和函数中定义变量之前使用global,因此代码如下所示。在

^{pr2}$

但现在它说“name”variable“未定义”。在

本质上,我怎样才能让变量'variable'用tkinter中的一个按钮改变呢?我是否错误地认为使用全局?在


Tags: 代码datatkinterdefbuttonwindowvariable按钮
1条回答
网友
1楼 · 发布于 2024-05-20 20:26:03

你用global有点不合适。你不需要在所有地方定义全局。让我们把它分解一下。在

您不需要在全局命名空间中定义全局命名空间。在

from tkinter import *
window = Tk()
myvar = "data" # this variable is already in the global namespace

这告诉函数在与变量myvar交互时检查全局命名空间。在

^{pr2}$

这个print语句之所以有效,是因为它在检查其他名称空间之后检查了全局变量名称空间,而没有找到变量myvar。在

def printVariable():
    print(myvar)

button1 = Button(window, command = changeVariable)
button1.pack()
button2 = Button(window, command = printVariable)
button2.pack()

window.mainloop()

所以如果我们把这些代码放在一起,我们就会得到想要的结果。在

from tkinter import *
window = Tk()
variable = "data"

def changeVariable():
    global variable
    variable = "different data"

def printVariable():
    print(variable)

button1 = Button(window, command = changeVariable)
button1.pack()
button2 = Button(window, command = printVariable)
button2.pack()

window.mainloop()

这将产生一个如下所示的窗口:

enter image description here

如果我们先按底部按钮,然后按顶部按钮,然后再按底部按钮,结果是:

enter image description here

相关问题 更多 >