首页 > 解决方案 > 无法在定义之外保存变量

问题描述

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

要测试我的代码,有一个接受和测试按钮。如果我可以输入一个数字,请按接受然后按测试它应该打印该数字。目前它打印类 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()

标签: pythonpython-3.xtkinter

解决方案


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

错字

看你的Accept()功能。第一行和第三行有一个a缺失。

globallocal变量之间的差异

您的脚本使用第fuel_stored2 行中声明的全局对象。您Accept()声明了另一个与第一个不同的本地对象。 fuel_storedPython 中的函数或方法将始终(隐式)使用对象的本地版本。解决方案是告诉您的函数使用带有关键字的全局对象,global如下所示

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

另请参阅在函数中使用全局变量

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

在这里,我使用内容变量为您提供了一个完全不同的解决方案。Entry()对象直接知道使用fuel_storedtextvariable=请参阅的构造函数中的参数Entry。我还把你的代码最小化了一点。

#!/usr/bin/env python3
from tkinter import *

def PrintFuel():
    print (fuel_stored.get())

root = Tk()

# Need to be instanciated it after Tk().
fuel_stored = StringVar()

number1 = Entry(root, textvariable=fuel_stored)
number1.pack()

nameButton = Button(root, text="Test", command=PrintFuel)
nameButton.pack()

root.mainloop()

推荐阅读