python - Python:在 Tkinter 应用程序中使用从一个函数到另一个函数的变量(文件名)
问题描述
我正在尝试将用户输入(文件名)用于另一个函数,但是在使用时出现错误,即使我已将其声明为突出显示的全局变量。非常感谢任何反馈。################################################# ##########################################
####Function I####
# upload action function
def UploadAction(event=None):
global filename
path = filedialog.askopenfilename()
statuslabel = Label(frame1, bd=1, padx=5,relief='ridge', justify=LEFT,bg="spring green")
statuslabel.configure(text="File opened sucessfully:\n" +path)
statuslabel.pack()
statuslabel.place(x=590, y=375, anchor='ne')
filename =ntpath.basename("{}".format(path))
button = Button(frame1,text = "Upload IOS", command =UploadAction)
button.pack()
button.place(x=300, y=370, anchor='ne')
print(filename) ## issue here as cant print
####Function II#####
def md5Verify():
command = "verify /md5" "flash:""{}".format(filename)
output = connection.send_command_timing(command, strip_prompt=False, strip_command=False,
delay_factor=5)
#print(output)
output = re.search(' = (\w+)', str(output))
#print(output.group(1))
md5_entry1 = "{}".format(md5_entry.get())
print(md5_entry1)
print("hello")
if md5_entry1 == str(output.group(1)):
print("MD5 checksum verified")
elif md5_entry1 != str(output.group(1)):
print("MD5 Hash mish match")
## issue here as cant use the variable in this function.
解决方案
这是如何在 tkinter 中使用全局变量的简化演示。
from tkinter import *
from tkinter import filedialog
root = Tk()
# default value
filename = None
def upload():
global filename
path = filedialog.askopenfilename()
# update value
filename = path
print("upload:", filename)
def verify():
# reusing a global variable in another function
global filename # this line is optional if we don't need to change the value of the global variable
# do something
if filename:
print("verify:", filename)
else:
print("value not set")
button = Button(root, text="Upload IOS", command=upload)
button.pack()
show_button = Button(root, text="Show filename", command=verify)
show_button.pack()
root.mainloop()
推荐阅读
- docusignapi - 如何在 DocuSign 中进行用户静默激活?
- datatables - 是什么导致了我的 Datatable 的布局问题?
- fiware-knowage - 无法登录 Knowage GUI
- javascript - jquery 2.2.3 未定义“数据”属性
- location - Anylogic - 由条件触发的代理位置
- javascript - 如何从javascript中的url获取指定的id
- python - 如何检查用户是否在 on_message 中具有特定角色?
- android - 运行 react-native run-android 显示“构建失败并出现异常”
- scala - 如何根据传递的参数从 RDD 中提取值
- wordpress - 更新帖子时自动重定向到 wp-admin/post