tkinter new class 不能使用 .get()/float()

tkinter new class can't use .get()/float()

我定义了一个新的 Entry 子类:NewEntry,但它无法获取其中的数字。我该如何解决这个问题?

当我点击按钮时,显示错误信息:

ValueError: could not convert string to float:
from Tkinter import *
root = Tk()                                                                                                                              

class NewEntry(Entry):
    def __init__(self,parent,cusdef='1'):      #Initiation default number is '1'                                      
        Entry.__init__(self,parent)
        self.cusdef = cusdef
        v=StringVar()
        v.set(self.cusdef)
        self = Entry(self,textvariable=v)
        self.pack()
        return

def GetNum():
    a=e.get()
    print float(a)
    return

e = NewEntry(root)
e.pack(fill='x')

button = Button(root,command=GetNum)
button.pack(fill='x')
root.mainloop()

您似乎试图在此处初始化您的 Entry 子类:

self = Entry(self,textvariable=v)
self.pack()

但是,您只是覆盖了名为 self 的变量并创建了一个新的 Entry,它被丢弃了。

相反,您需要使用正确的参数执行一次 Entry.__init__ 调用:

class NewEntry(Entry):
    def __init__(self,parent,cusdef='1'):
        self.cusdef = cusdef
        v=StringVar()
        v.set(self.cusdef)
        Entry.__init__(self,parent, textvariable=v)
        self.pack()
        return