Home > Enterprise >  why is the location string not showing in the window. tkinter python?
why is the location string not showing in the window. tkinter python?

Time:02-07

im trying to write a code that will tell you if the location is a file or directory. if its a file, then it will read the file. here is my code (ik its very bad, im sorry)

import os
import tkinter as tk

screen = tk.Tk()
screen.title("files and directories")
screen.geometry("300x100")

def FileDir():
    path = location.get(1.0, "end-1c")
    location.delete(1.0, tk.END)

    if os.path.exists(path):
        print("✔ - this location exists")

        info_location = tk.Label(screen, text=f"location: {location}")
        info_location.pack()

        if os.path.isfile(path):
            print("\tthis is a file")
            type = 'file'

            info_type = tk.Label(screen, text=f"type: {type}")
            info_type.pack()

            while True:
                open_file = input("\nDo you want to read this file? ")

                if open_file.lower() == 'yes':
                    with open(path) as file:
                        contents = file.read()
                    print(contents)
                    break

                elif open_file.lower() == 'no':
                    print("goodbye!")
                    break

                else:
                    print("invalid input")
                    continue

        elif os.path.isdir(path):
            print("\tthis is a directory")
            type = 'directory'

            info_type = tk.Label(screen, text=f"type: {type}")
            info_type.pack()

    else:
        print("✘ - this location doesn't exist")

text = tk.Label(screen, text="Enter file/directory location: ")
text.pack()

location = tk.Text(screen, height = 1, width = 25)
location.pack()

enter_btn = tk.Button(screen, text="Enter", command=FileDir)
enter_btn.pack()

screen.mainloop()

so when putting the location of a string, everything works fine except that the location doesnt show and instead it shows ".!text". anyone know why?

CodePudding user response:

location is a widget rather than a string. The string representation of a tkinter widget is its internal name. Thus, when you do text=f"location: {location}" you are creating a string that contains the name of the widget rather than the contents.

To display the contents you must fetch them from the widget. You're already doing that when you define path, so you just need to use {path} rather than {location}

text=f"location: {path}"
  •  Tags:  
  • Related