首页 > 解决方案 > 如何从 Tkinter 中的条目小部件给出名称的文件中读取?

问题描述

我是 python 的新手,甚至是 Tkinter 的新手。我试图让用户在条目小部件中输入文件名,然后点击一个按钮,将输入文件的内容输出到控制台。按下 button_1(第 46 行)后,attributeFileName() 方法(第 7 行)出现问题。下面是我的代码:

from Tkinter import *
import tkMessageBox

root = Tk()
root.configure(background="black")

def attributeFileName():  
   try:
     f = open(entry_1.get(), 'r')  # Tries to open the file entered by the 
       except IOError:
     print ("Cannot open", entry_1.get())  # If the file cannot be opened, 
report it back to the user
   for line in f:
     print line
   f.close()

def constraintFileName():
   print(entry_2.get())

def preferenceFileName():
   print(entry_3.get())

# *****Frames*****

fileFrame = Frame(root)
fileFrame.configure(background="black")
fileFrame.pack(pady=50)
attributeFrame = Frame(root)
attributeFrame.configure(background="red")
attributeFrame.pack(pady=5)
constraintFrame = Frame(root)
constraintFrame.configure(background="blue")
constraintFrame.pack(pady=5)
preferenceFrame = Frame(root)
preferenceFrame.configure(background="#51006F")
preferenceFrame.pack()

# *****File Frame*****

label_1 = Label(fileFrame, text="Enter Attributes file name:", anchor="e", 
bg="red", font="Times 25", width=25, height=1)
label_2 = Label(fileFrame, text="Enter hard constraints file name:", 
anchor="e", bg="blue", fg="yellow", font="Times 25", width=25, height=1)
label_3 = Label(fileFrame, text="Enter preferences file name:", 
anchor="e", bg="#51006F", fg="#45FFF4", font="times 25", width=25, 
height=1)
entry_1 = Entry(fileFrame, font="Times 25")
entry_2 = Entry(fileFrame, font="Times 25")
entry_3 = Entry(fileFrame, font="Times 25")

button_1 = Button(fileFrame, text="Submit", bg="red", font="Times 20", 
command=attributeFileName)
button_2 = Button(fileFrame, text="Submit", bg="blue", fg="yellow", 
font="Times 20", command=constraintFileName)
button_3 = Button(fileFrame, text="Submit", bg="#51006F", fg="#45FFF4", 
font="Times 20", command=preferenceFileName)
label_1.grid(row=0, column=0, padx=5, pady=5)
entry_1.grid(row=0, column=1)
button_1.grid(row=0, column=2, padx=5, pady=5)

label_2.grid(row=1, column=0, padx=5, pady=5)
entry_2.grid(row=1, column=1)
button_2.grid(row=1, column=2, padx=5, pady=5)

label_3.grid(row=2, column=0, padx=5, pady=5)
entry_3.grid(row=2, column=1)
button_3.grid(row=2, column=2, padx=5, pady=5)

# *****Attribute Frame*****
attributeHeaderFrame = Frame(attributeFrame)
attributeHeaderFrame.configure(background="red")
attributeHeaderFrame.grid(row=0)
attributeDataFrame = Frame(attributeFrame)
attributeDataFrame.configure(background="red")
attributeDataFrame.grid(row=1)
attributeListFrame = Frame(attributeFrame)
attributeListFrame.configure(background="red")
attributeListFrame.grid(row=2, pady=10)

label_Attribute_header = Label(attributeHeaderFrame, text="Attributes", 
bg="red", font="Times 25", width=25, height=1)
attribute_Name = Label(attributeDataFrame, text="Name:", bg="red", 
font="Times 20")
entry_Attribute_Name = Entry(attributeDataFrame, font="Times 20")
label_Colon = Label(attributeDataFrame, text=":", bg="red", font="Times 
20")
label_Comma = Label(attributeDataFrame, text=",", bg="red", font="Times 
25") 
entry_Attribute1 = Entry(attributeDataFrame, font="Times 20")
entry_Attribute2 = Entry(attributeDataFrame, font="Times 20")
attribute_add = Button(attributeDataFrame, text="+", bg="black", 
fg="white", font="Times 15")

list = Listbox(attributeListFrame, height=15, width=172)
scroll = Scrollbar(attributeListFrame, command=list.yview)

list.configure(yscrollcommand = scroll.set)
list.pack(side=LEFT)
scroll.pack(side=RIGHT, fill=Y)

label_Attribute_header.pack()
attribute_Name.grid(row=0, column=0, padx=5, pady=5, sticky="W")
entry_Attribute_Name.grid(row=0, column=1, sticky="W")
label_Colon.grid(row=0, column=2, sticky="W")
entry_Attribute1.grid(row=0, column=3, sticky="W", padx=(50,0))
label_Comma.grid(row=0, column=4, sticky="W")
entry_Attribute2.grid(row=0, column=5, sticky="W")
attribute_add.grid(row=0, column=6, padx=5, pady=5, sticky="W")

# *****Constraint Frame*****
constraintHeaderFrame = Frame(constraintFrame)
constraintHeaderFrame.configure(background="blue")
constraintHeaderFrame.grid(row=0)
constraintDataFrame = Frame(constraintFrame)
constraintDataFrame.configure(background="blue")
constraintDataFrame.grid(row=1, pady=10)
constraintListFrame = Frame(constraintFrame)
constraintListFrame.configure(background="blue")
constraintListFrame.grid(row=2, pady=10)

label_Constraint_header = Label(constraintHeaderFrame, text="Hard 
Constraints", bg="blue", fg="yellow", font="Times 25")
label_Constraints = Label(constraintDataFrame, text="Constraint:", 
bg="blue", fg="yellow", font="Times 20",)
entry_Constraints = Entry(constraintDataFrame, font="Times 20")
constraint_add = Button(constraintDataFrame, text="+", bg="black", 
fg="white", font="Times 15")
label_Constraint_header.pack()
label_Constraints.grid(row=0)
entry_Constraints.grid(row=0, column=1)
constraint_add.grid(row=0, column=2, padx=15)

list = Listbox(constraintListFrame, height=15, width=172)
scroll = Scrollbar(constraintListFrame, command=list.yview)

list.configure(yscrollcommand = scroll.set)
list.pack(side=LEFT)
scroll.pack(side=RIGHT, fill=Y)

# *****Preference Frame*****

preferenceHeaderFrame = Frame(preferenceFrame)
preferenceHeaderFrame.configure(background="#51006F")
preferenceHeaderFrame.grid(row=0)
preferenceDataFrame = Frame(preferenceFrame)
preferenceDataFrame.configure(background="#51006F")
preferenceDataFrame.grid(row=1, pady=10)
preferenceListFrame = Frame(preferenceFrame)
preferenceListFrame.configure(background="#51006F")
preferenceListFrame.grid(row=2, pady=10)

label_Preference_header = Label(preferenceHeaderFrame, text="Preferences", 
bg="#51006F", fg="#45FFF4", font="Times 25")
label_preference = Label(preferenceDataFrame, text="Preference:", 
bg="#51006F", fg="#45FFF4", font="Times 20",)
entry_preference = Entry(preferenceDataFrame, font="Times 20")
preference_add = Button(preferenceDataFrame, text="+", bg="black", 
fg="white", font="Times 15")

label_Preference_header.pack()
label_preference.grid(row=0)
entry_preference.grid(row=0, column=1)
preference_add.grid(row=0, column=2, padx=15)

list = Listbox(preferenceListFrame, height=15, width=172)
scroll = Scrollbar(preferenceListFrame, command=list.yview)

list.configure(yscrollcommand = scroll.set)
list.pack(side=LEFT)
scroll.pack(side=RIGHT, fill=Y)

root.mainloop()

我的输出:

样本输出

我希望从条目小部件中读取文件的名称,并将文件内容打印到控制台。但是,会引发异常。这是堆栈跟踪:

('Cannot open', 'test.txt')
Exception in Tkinter callback
Traceback (most recent call last):
  File "Tkinter.py", line 1542, in __call__
    return self.func(*args)
  File "gui.py", line 13, in attributeFileName
    for line in f:
UnboundLocalError: local variable 'f' referenced before assignment

有人可以向我解释这意味着什么,为什么我会收到这个错误,最重要的是如何解决它?谢谢

标签: pythonpython-2.7filetkinterio

解决方案


在这个函数中:

def attributeFileName():  
    try:
        f = open(entry_1.get(), 'r')  # Tries to open the file entered by the 
    except IOError:
        print ("Cannot open", entry_1.get())  # If the file cannot be opened, report it back to the user
    for line in f:
        print (line)
    f.close()

如果捕获到异常,f则未定义并导致您的未绑定错误。只需移动for循环并close在 try 语句中:

def attributeFileName():
    try:
        f = open(entry_1.get(), 'r')
        for line in f:
            print(line)
        f.close()
    except IOError:
        print ("Cannot open", entry_1.get())

推荐阅读