3

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?

4
  • 1
    Have you considered reading tkinter's Label documentation? Commented Sep 17, 2017 at 11:52
  • I have and I have made a minor breakthrough: I forgot to put text=fToOpen.read() but now in the Label, it is displaying the console error... Commented Sep 17, 2017 at 11:59
  • I have solved it now. I asked to open the file instead of file name then displayed the file in text=fToOpen.read() - Thankyou! Commented Sep 17, 2017 at 12:02
  • Are you sure print(fToOpen.read()) <-- ##This works## really works? Commented Aug 3, 2020 at 3:24

1 Answer 1

7

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.