首页 > 解决方案 > 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.
      

标签: pythontkinter

解决方案


这是如何在 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()


推荐阅读