![](/img/trans.png)
[英]unable to use variable of one function to another function in tkinter python
[英]Python: Use of variables (filename) from one function to another in Tkinter application
我正在尝试将用户输入(文件名)使用到另一个函数中,但是在使用时出现错误,即使我已将其声明为突出显示的全局变量。 非常感谢任何反馈。 ############################################### #########################################
####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()
# declare the variable at the beginning
global filename
# 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
# 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.