为什么位置字符串没有显示在窗口中.tkinter python



im试图编写一段代码,告诉您位置是文件还是目录。如果它是一个文件,那么它将读取该文件。这是我的代码(我很抱歉(

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

因此,当放置字符串的位置时,除了位置不显示,而是显示"之外,一切都很好;。!文本";。有人知道为什么吗?

location是一个小部件,而不是字符串。tkinter小部件的字符串表示是其内部名称。因此,当您执行text=f"location: {location}"时,您正在创建一个字符串,该字符串包含小部件的名称,而不是内容。

要显示内容,您必须从小部件中获取它们。当您定义path时,您已经在这样做了,所以您只需要使用{path}而不是{location}

text=f"location: {path}"

相关内容

  • 没有找到相关文章

最新更新