总是获取没有文件

时间:2019-07-17 17:43:49

标签: python

我正在尝试使用Python和Tkinter获取文件,这就是我拥有的:

opacity: 0.2;
filter: alpha(opacity=20

无论我尝试了什么,选择文件时,我总会得到file1 = "" file2 = "" file1entry = Entry().pack() file2entry = Entry().pack() def OpenFile1(): name = askopenfilename(initialdir="C:/Users/", filetypes=(("Text File", "*.txt"), ("All Files", "*.*")), title="Choose a file." ) # Using try in case user types in unknown file or closes without choosing a file. try: with open(name, 'r') as UseFile: file1 = UseFile file1entry.text = file1 except: print("No file exists") 我在做什么错了?

1 个答案:

答案 0 :(得分:0)

file1entry在功能范围内不存在,因此,当您尝试定义其.text属性时,会收到错误消息。

Python要求您明确声明变量是否为全局变量。

如果放置线

global file1entry 

该功能的顶部,它应该可以工作。

这将生成新代码:

file1 = ""
file2 = ""

file1entry = Entry().pack()
file2entry = Entry().pack()

def OpenFile1():
    global file1entry 
    name = askopenfilename(initialdir="C:/Users/",
                           filetypes=(("Text File", "*.txt"),
                                      ("All Files", "*.*")),
                           title="Choose a file."
                           )
    # Using try in case user types in unknown file or closes without choosing a file.
    try:
        with open(name, 'r') as UseFile:
            file1 = UseFile
            file1entry.text = file1
    except:
        print("No file exists")