简体   繁体   English

在Tkinter Python中打开和读取文本文件

[英]Open and Read text files in Tkinter Python

I'm trying to create a notepad-type program in Tkinter and Can't work out how to display a file's contents to a Label... 我正在尝试在Tkinter中创建一个记事本类型的程序,无法解决如何将文件内容显示到标签中的问题。

I have been able to display it's contents to the pyCharm shell but when I try to show in a label I get an error. 我已经能够将其内容显示到pyCharm shell中,但是当我尝试在标签中显示时,出现错误。

def openFile():
    fToOpen = filedialog.askopenfilename(filetypes=[("Text files","*.txt")])
    #print(fToOpen.read()) <-- ##This works##
    fileToOpen = open(fToOpen, 'r')
    Label(root, fileToOpen.read()).pack() <-- ##This doesn't##
    fToOpen.close()

The error I get is: 我得到的错误是:

 Traceback (most recent call last): File "C:\\Users\\Hello\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\tkinter\\__init__.py", line 1699, in __call__ return self.func(*args) File "C:/Users/Hello/Documents/html/Python/Prog.py", line 143, in openFile Label(root, fileToOpen.read()).pack(fill=Y) File "C:\\Users\\Hello\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\tkinter\\__init__.py", line 2760, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "C:\\Users\\Hello\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\tkinter\\__init__.py", line 2289, in __init__ classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)] AttributeError: 'str' object has no attribute 'items' 

Can anyone help me? 谁能帮我?

This is actually rather simple. 这实际上很简单。

All you need to do is open the file and read the information into the text attribute of the widget. 您需要做的就是打开文件,然后将信息读取到小部件的text属性中。

This can be done as below: 可以按照以下步骤完成:

from tkinter import *

root = Tk()

with open("file.txt", "r") as f:
    Label(root, text=f.read()).pack()

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM