Cobain Ambrose
Cobain Ambrose

Reputation: 91

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...

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.

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?

Upvotes: 3

Views: 16268

Answers (1)

Ethan Field
Ethan Field

Reputation: 4730

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.

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()

Upvotes: 7

Related Questions