如何修复Tkinter中的entry.get()函数?

2024-04-20 14:13:07 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个非常愚蠢的项目,用来测试我在python 3.8中的绝对初学者技能。但我得到了以下错误:

AttributeError: 'NoneType' object has no attribute 'get'

我不知道怎么了

import tkinter as tk

window = tk.Tk()
window.title('File Writer')

def getfile():
    text1 = entry1.get()
    text2 = entry2.get()
    text3 = entry3.get()
    text4 = entry4.get()
    fl = fl.get
    save = open('C:\\Users\\Anas\\Desktop\\' + fl + '.txt', 'w')
    save.write('Your name: ' +  text1 + '\n')
    save.write('Your Birthdate: ' + text2 + '\n')
    save.write('Your City: ' + text3 + '\n')
    save.write('Your Work: ' + text4 + '\n')
    save.close()


tk.Label(window, text='Welcome to file writer', font="Times 22 bold").pack()
tk.Label(window, text="What is your full name?").pack()
entry1 = tk.Entry(window).pack()
tk.Label(window, text="When is your birthdate (DD/MM/YYYY").pack()
entry2 = tk.Entry(window).pack()
tk.Label(window, text="Where do you live? (City, State, Country").pack()
entry3 = tk.Entry(window).pack()
tk.Label(window, text="What is your job? (position/company)").pack()
entry4 = tk.Entry(window).pack()
tk.Label(window, text='What do you want to name your file').pack()
entry5 = tk.Entry(window).pack()
tk.Button(window, text="Click to save your file", font='Arial 20', command=getfile).pack()


window.mainloop()

1条回答
网友
1楼 · 发布于 2024-04-20 14:13:07

当您定义条目时,您使用.pack()方法,但是pack、grid或place不返回元素(tk.entry),但是不返回任何元素,因此当您最终使用.pack()定义元素时

entry1 = tk.Entry(window).pack() # .pack() -> returns None

变量entry1的值设置为None

要解决这个问题,可以先定义变量,然后添加包

entry1 = tk.Entry(window) # now the element is stored in the variable
entry1.pack()

我建议你改变路径C:\\Users\\Anas\\Desktop\\

输入到用户的输入,以便它可以用于其他计算机 或者做类似的事情

import getpass
path = f'C:\\Users\\{getpass.getuser()}\\Desktop\\'

相关问题 更多 >