如何从def中取出数据



我试过这个代码

from tkinter import *
from tkinter import filedialog

def browseFiles():
open_f = filedialog.askopenfile(mode='w', defaultextension='.xls')
path_f = open_f.name
print (path_f)

window = Tk()
windowWidth = window.winfo_reqwidth()
windowHeight = window.winfo_reqheight()
positionRight = int(window.winfo_screenwidth()/2 - windowWidth/2)
positionDown = int(window.winfo_screenheight()/2 - windowHeight/2)
window.geometry("+{}+{}".format(positionRight, positionDown))
window.title('Choose Your Excel file')
window.geometry("300x100")
window.config(background = "white")    
button_explore = Button(window, text = "Browse Files",height=2,width=20,command = browseFiles 
,bg='white')
button_explore.place(x=75,y=20)
window.resizable(False, False)
window.mainloop()
print (path_f)

它可以在第一种情况下绘制,但不能在第二种情况下绘制。它只能在定义的函数中绘图,而它正在被擦除。

C:/Users/Dell/OneDrive/Pictures/Untitled.png
Traceback (most recent call last):
File "C:/Users/Dell/Desktop/sample.py", line 25, in <module>
print (path_f)
NameError: name 'path_f' is not defined

请问谁能指点一下

由于path_f是在函数内部创建的,它只属于函数(局部变量),所以您可以做的是,通过说global path_f:

使其全局
def browseFiles():
global path_f
open_f = filedialog.askopenfile(mode='w', defaultextension='.xls')
path_f = open_f.name
print(path_f)

现在path_f可以在代码中的任何地方使用,只要在使用它之前定义它。

您可以简单地将path_f声明为全局变量,如下所示:

def browseFiles():
global path_f
open_f = filedialog.askopenfile(mode='w', defaultextension='.xls')
path_f = open_f.name
print (path_f)

相关内容

  • 没有找到相关文章

最新更新