无法保存定义外的变量

时间:2019-06-16 03:50:20

标签: python python-3.x tkinter

在我的程序内部有一个定义,可以在该窗口中打开一个窗口(该窗口是下面的代码),我希望能够使用输入框设置变量,然后在窗口外部可以调用该变量与设置的整数。

要测试我的代码,有一个接受和测试按钮。如果我可以输入数字,请按接受,然后按测试,它将打印该数字。目前它会打印int类。

from tkinter import *
fuel_stored = int

def Accept():
    Varible = number1.get()
    fuel_stored = Variable
    print (Varible)

def PrintFuel():
    print (fuel_stored)

root = Tk()
root.geometry=("100x100+100+50")

number1 = Entry(root, bg="white")
number1.pack()
number1.focus_force()


nameButton = Button(root, text="Accept", command=Accept)
nameButton.pack(side=BOTTOM, anchor=S)
nameButton = Button(root, text="Test", command=PrintFuel)
nameButton.pack(side=BOTTOM, anchor=S)


root.mainloop()

1 个答案:

答案 0 :(得分:2)

您的代码中存在一些“问题”。

错字

请参阅您的const wb_odometry &函数。第一和第三行中缺少Accept()

aglobal变量之间的差异

您的脚本使用第2行中声明的全局对象local。您的fuel_stored声明了另一个与第一个对象不同的 local Accept()对象。 Python中的函数或方法将始终(隐式)使用对象的本地版本。解决方案是像这样告诉您的函数使用带有关键字fuel_stored的全局对象

global

为此也请参见Using global variables in a function

具有内容变量的不同解决方案

在这里,我为您提供一个使用content变量的完全不同的解决方案。 def Accept(): Variable = number1.get() print (Variable) global fuel_stored fuel_stored = Variable 对象知道直接使用Entry()。请参见fuel_stored的构造函数中的参数textvariable=。我还最小化了您的代码。

Entry