Python 如何在tkinter上设置条目的默认值?

Python 如何在tkinter上设置条目的默认值?,python,tkinter,Python,Tkinter,我在做一个表格,它是这样的 from tkinter import * root = tk.Tk() root.title("Form") name = Label(root, text="Name", width=20,bg = "black", fg="red") name.place(x=150, y=50) name = Entry(root, width=20, bg = "black&quo

我在做一个表格,它是这样的

from tkinter import *
root = tk.Tk()
root.title("Form")

name = Label(root, text="Name", width=20,bg = "black", fg="red")
name.place(x=150, y=50)

name = Entry(root, width=20, bg = "black", fg="red")
name.place(x=150, y=100)

print(name.get)
假设有人把“姓名”留空我想让我的代码检测到并打印“未知” 非但没有

提示:我不希望条目中包含已写入未知的文本,我希望可以将其留空,并且我的打印仍然可以打印未知

浮动的问题:

def submit():
    kilograms = entry_kilo.get()
    kilo_float = float(kilograms)

下面是我创建的一个类,它支持这种类型的活动

from tkinter import *

class Custom(Entry): #inheriting from the Entry class
    def ret(self):
        if self.get() == '': # if empty then assign
            return 'Unknown'
        else:
            return self.get() # else give the same thing out

root = Tk()
root.title("Form")

name = Label(root, text="Name", width=20,bg = "black", fg="red")
name.place(x=150, y=50)

a = Custom(root, width=20, bg = "black", fg="red") #instantiating using all the same option you did before
a.place(x=150, y=100)

print(a.ret()) #Prints unknown
print(a.ret() == a.get()) #prints false obviously, just a testimony ;)

root.mainloop()
这里您必须使用
a.ret()
,为什么?因为我在课堂上就是这样定义的。您可以使用
a.get()
,但它只会给出通常的空白字符串。 我认为除了编辑tkinter的
\uu init\uuuuuuuuy.py
文件之外,不可能覆盖现有的
get()
方法,如果我错了,一定要告诉我

您还可以将类缩短为多行上的一点,如:

class Custom(Entry):
    def ret(self):
        return 'Unknown' if self.get() == '' else self.get() #does the same thing as before
请记住,您可以用任何您喜欢的内容替换
'Unknown'

这不是最好的代码,因为我以前没有使用过类。为什么要使用类?因为我相信默认的tkinter是不可能的。那么,为什么不创建一个自定义类并获得这种效果;)

你应该如何在你的项目中使用这个?只需将所有
条目(..)
替换为
自定义(..)
。它支持普通的
条目
小部件所做的所有选项

在此处进行更改以修复错误:

def click():
    kilograms = a.ret()
    kilo_float = a.ret()
    try:
        kilo_float = float(kilograms)
    except ValueError:
        pass
    print(kilo_float)
希望这对你有帮助。如果您有任何疑问或错误,请务必告诉我


干杯

你考虑过修改印刷品吗?这会更简单更快:
print(name.get if name.get!=“else”Unknown”)
我想这是可能的,但我正在使用factor maker制作一个模板,它将我填写的表单的输出发送到word文件。条目值进入一个字典,该字典表示如下上下文:{name:'entry_name'},然后进入docx文件,它用于普通字符串。我用float条目尝试了它,它给了我ValueError:无法将字符串转换为float:“”如果您能帮我,我将不胜感激。(不幸的是,我不能向上投票,因为我的代表是低的)例如:a=Custom(root,width=20,bg=“black”,fg=“red”)float\u a=float(a)@float,应该是
float\u a=float(a.ret())
,但如果编辑代码时框为空,它仍会显示相同的错误。加上我的错误。我希望能够将float条目留空,并获得“0”