python - 无法在定义之外保存变量
问题描述
在我的程序内部有一个定义在这个窗口中打开一个窗口(这个窗口是下面的代码)我希望能够使用输入框设置一个变量,然后在窗口之外能够使用集合调用该变量整数。
要测试我的代码,有一个接受和测试按钮。如果我可以输入一个数字,请按接受然后按测试它应该打印该数字。目前它打印类 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()
解决方案
您的代码存在一些“问题”。
错字
看你的Accept()
功能。第一行和第三行有一个a
缺失。
global
和local
变量之间的差异
您的脚本使用第fuel_stored
2 行中声明的全局对象。您Accept()
声明了另一个与第一个不同的本地对象。 fuel_stored
Python 中的函数或方法将始终(隐式)使用对象的本地版本。解决方案是告诉您的函数使用带有关键字的全局对象,global
如下所示
def Accept():
Variable = number1.get()
print (Variable)
global fuel_stored
fuel_stored = Variable
另请参阅在函数中使用全局变量。
具有内容变量的不同解决方案
在这里,我使用内容变量为您提供了一个完全不同的解决方案。Entry()
对象直接知道使用fuel_stored
。textvariable=
请参阅的构造函数中的参数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()
推荐阅读
- typescript - 如何在加载时捕获模块抛出的异常?
- ios - SwiftUI NavigationBarTitle 上面的字幕,就像在 Apple Music 中一样?
- java - 如何在 c 和 fortran 中使用 Renjin Maven 插件
- flutter - 检查 StreamSubscription 是否被取消
- java - Spring Security 无法调用 ldap 自定义提供程序
- python - 在python中从给定的json文件创建树
- azure - 如何使用 Excel Online Flow 连接器从 Azure 文件存储加载文件?
- c++ - 使用 Rcpp 返回 GMP 类
- appium - WebDriverException:未知的服务器端..原始错误:-[FBApplication resolve]: unrecognized selector sent to instance
- scala - 很高兴从给定的字符串中找到特定的句子?