【发布时间】:2019-11-24 16:05:40
【问题描述】:
我正在做一个小项目来帮助我巩固对 python 的学习。经过无休止的全局变量尝试,并返回;和搜索我决定在这里发帖。基本上,当程序运行时,用户可以从他们的计算机中选择一个 .txt 文件,然后通过 findFile() 函数特别是 my_label 变量记录目录。我想使用存储在 my_label 中的字符串将其放在 editFile 函数中,特别是以下行: my_file = open("File location goes here","a+") 其中看起来像 my_file = open(my_label,"a+" )。如果有人能提供帮助,我将不胜感激。
root = tk.Tk()
canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()
entry1 = tk.Entry (root)
canvas1.create_window(200, 140, window=entry1)
def editFile ():
x1 = entry1.get()
label1 = tk.Label(root, text=x1 )
canvas1.create_window(200, 230, window=label1)
my_file = open("File location goes here","a+")
my_file.read()
my_file.write("\n" + x1)
my_file.close()
def findFile ():
root.filename = filedialog.askopenfilename(initialdir="C:\\Users\\mypc",
title="Select A File", filetypes=(("txt files", "*.txt"),("All Files", "*.*")))
my_label = Label(root, text=root.filename).pack()
canvas1.create_window(200, 290, window=my_label)
button1 = tk.Button(text='Enter Text', command=editFile)
canvas1.create_window(200, 180, window=button1)
button2 = tk.Button(text='Exit', command=root.destroy)
canvas1.create_window(200, 250, window=button2)
button3 = tk.Button(text='Find File', command=findFile)
canvas1.create_window(200, 270, window=button3)
root.mainloop()
【问题讨论】:
-
在
my_label中,您既不存储任何字符串,也不存储Label,而是None,因为pack()总是返回None。您必须分两步完成my_label = tk.Label()和my_label.pack()。但是你在root.filename中有你的文本,所以在editFile中使用它。 -
“在对全局变量进行无休止的尝试后,然后返回”:阅读Best way to structure a tkinter application 以摆脱使用
global。 -
如果你把小部件 (
my_label') on Canvas then you don't needpack()/grid()/place()`
标签: python function file variables tkinter