为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蝴蝶不菲 2023-08-08 09:43:48
我正在尝试制作一个表格,它是这样的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)
查看完整描述

1 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

这是我制作的一个课程,以便它支持此类活动。


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(),但它只会给您通常的空白字符串。get()而且我认为除了编辑__init__.pytkinter 文件之外不可能覆盖现有方法,如果我错了,请告诉我。


您还可以将类缩短为多行,例如:


class Custom(Entry):

    def ret(self):

        return 'Unknown' if self.get() == '' else self.get() #does the same thing as before

请记住,您可以替换'Unknown'为您喜欢的任何内容。


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


您应该如何在您的项目中使用它?只需将所有替换Entry(..)为Custom(..). 它也支持普通小部件所做的所有选项Entry。


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


def click():

    kilograms = a.ret()

    kilo_float = a.ret()

    try:

        kilo_float = float(kilograms)

    except ValueError:

        pass

    print(kilo_float)

希望这对您有帮助。如果您有任何疑问或错误,请告诉我。


查看完整回答
反对 回复 2023-08-08
  • 1 回答
  • 0 关注
  • 69 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信