【问题标题】:Can not use entry's get method inside my function [duplicate]无法在我的函数中使用条目的 get 方法[重复]
【发布时间】:2023-03-06 05:14:01
【问题描述】:
from tkinter import *

def login():
    root = Tk()
    root.resizable(False, False)
    root.title("Log in")
    root.geometry("300x200")
    root.configure(bg='#AFFDFF')

    def submit(usernameEntry):
        with open("username.txt", "w") as myFile:
            myFile.write(usernameEntry.get())

    Label(root, text="Please enter your username", bg='#AFFDFF').place(relx=0.5, rely=0.35, 
        anchor=CENTER)
    usernameEntry = Entry(root, width=25).place(relx=0.5, rely=0.5, anchor=CENTER)
    submitBtn = Button(root, text="Submit", bg='#A4FFCB', command=lambda: 
        submit(usernameEntry)).place(relx=0.5, rely=0.65, anchor=CENTER)

    root.mainloop()

我的输出是:

Traceback (most recent call last):
  File "C:\Users\george\anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "c:\Users\george\Desktop\rock paper scissors\interface.py", line 48, in <lambda>
    submitBtn = Button(root, text="Submit", bg='#A4FFCB', command=lambda: 
    submit(usernameEntry)).place(relx=0.5, rely=0.65, anchor=CENTER)
  File "c:\Users\george\Desktop\rock paper scissors\interface.py", line 44, in submit
    myFile.write(usernameEntry.get())
AttributeError: 'NoneType' object has no attribute 'get'

请帮我解决这个问题。我现在被困了一段时间。 我也尝试过不引用“usernameEntry”来提交函数,但它不起作用。

【问题讨论】:

  • 在提供代码sn-p时,请提供可以独立运行的代码。您的代码缺少这些行:from tkinter import Tk, Label, Entry, Button, CENTERroot = Tk()

标签: python tkinter get window


【解决方案1】:

根据@acw1668 共享的链接,您的代码中的.place 返回None,而不是入口对象,因此您的行:

usernameEntry = Entry(root, width=25).place(relx=0.5, rely=0.5, anchor=CENTER)

表示usernameEntry = None 所以该行需要变成:

usernameEntry = Entry(root, width=25)
usernameEntry.place(relx=0.5, rely=0.5, anchor=CENTER)

这对你的其他变量也是一样的,例如:

submitBtn = Button(root, text="Submit", bg='#A4FFCB', command=lambda: submit(usernameEntry)).place(relx=0.5, rely=0.65, anchor=CENTER)

应该是:

submitBtn = Button(root, text="Submit", bg='#A4FFCB', command=lambda: submit(usernameEntry))
submitBtn.place(relx=0.5, rely=0.65, anchor=CENTER)

【讨论】:

    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2019-11-29
    • 2016-07-18
    • 2016-03-26
    • 2011-05-08
    相关资源
    最近更新 更多