如何在 Tkinter 的输入字段中只允许某些参数 [英] How to only allow certain parameters within an entry field on Tkinter

查看:36
本文介绍了如何在 Tkinter 的输入字段中只允许某些参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想要一个 Tkinter 中的输入框,它只接受大于或等于 0.0 且小于或等于 1.0 的浮点数,我该怎么做?

If i want an entry box in Tkinter that only accepts floating point numbers that are greater than or equal to 0.0 and less than or equal to 1.0 how would i do that?

推荐答案

正确使用 tkinter 的验证功能.但它确实是一个 PIA 使用.

The proper way it to use tkinter's validate capabilities. But it's really a PIA to use.

dsgdfg 有一个很好的答案,但我可以让它更简洁、更健壮、更动态:

dsgdfg has a good answer, but I can make that a lot neater, robust, and more dynamic:

import Tkinter as tk

class LimitedFloatEntry(tk.Entry):
    '''A new type of Entry widget that allows you to set limits on the entry'''
    def __init__(self, master=None, **kwargs):
        self.var = tk.StringVar(master, 0)
        self.var.trace('w', self.validate)
        self.get = self.var.get
        self.from_  = kwargs.pop('from_', 0)
        self.to = kwargs.pop('to', 1)
        self.old_value = 0
        tk.Entry.__init__(self, master, textvariable=self.var, **kwargs)

    def validate(self, *args):
        try:
            value = self.get()
            # special case allows for an empty entry box
            if value not in ('', '-') and not self.from_ <= float(value) <= self.to:
                raise ValueError
            self.old_value = value
        except ValueError:
            self.set(self.old_value)

    def set(self, value):
        self.delete(0, tk.END)
        self.insert(0, str(value))

您可以像使用 Entry 小部件一样使用它,除了现在您有 'from_' 和 'to' 参数来设置允许范围:

You use it just like an Entry widget, except now you have 'from_' and 'to' arguments to set the allowable range:

root = tk.Tk()
e1 = LimitedFloatEntry(root, from_=-2, to=5)
e1.pack()
root.mainloop()

这篇关于如何在 Tkinter 的输入字段中只允许某些参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆