[英]AttributeError: 'str' object has no attribute 'get' when trying to get string information from a tkinter Entry Widget
[英]Why am I getting this error when trying to get text from an entry object: Tkinter AttributeError: CustomClass instance has no attribute 'entry'?
I am new to Tkinter and I have already troubleshot by simplifying my class, and also reading this other question on stack: "Why is Tkinter Entry's get function returning nothing?" 也沒有幫助。
我想調用一個使用entry.get()
方法將用戶輸入打印到控制台的 function。
from tkinter import *
class UserInterface:
def __init__(self, master):
lbl1 = Label(root, text="Enter graph size:")
lbl1.grid(row=1, sticky=E)
entry1 = Entry(root)
entry1.grid(row=1, column=5)
printButton = Button(root, text="Print")
printButton.bind("<Button-1>", self.printSize)
printButton.grid(row=2,column=10)
def printSize(self, event):
print("Testing: " + self.entry1.get())
root = Tk()
c = UserInterface(root)
root.geometry('500x500')
root.title('Tkinter Testing')
root.mainloop()
這是拋出的完整異常:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1547, in __call__
return self.func(*args)
File "testing.py", line 21, in printSize
print("Testing: " + self.entry1.get())
AttributeError: UserInterface instance has no attribute 'entry1'
沒有self.entry1
,因為您從未定義self.entry1
。 你只做了entry1 = Entry(root)
,而那應該是self.entry1 = Entry(root)
。 唯一不顯式編寫self
的情況是,如果您在 class 內部,但在init
或任何其他 function 之外定義某些內容,例如:
class UserInterface:
entry1 = None # accessible via self.entry1
def __init__(self, master):
...
self.entry1 = Entry(root)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.