限制 Tkinter Entry 小部件中的值 [英] Restricting the value in Tkinter Entry widget

查看:64
本文介绍了限制 Tkinter Entry 小部件中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 Entry 小部件中的值限制为仅数字.我实现的方式是:

I need to restrict the values in the Entry widget to numbers only. The way I implemented is:

import numpy as np
from Tkinter import *;
import tkMessageBox;

class window2:

    def __init__(self,master1):

        self.panel2=Frame(master1)
        self.panel2.grid()

        self.button2=Button(self.panel2,text="Quit",command=self.panel2.quit)
        self.button2.grid()

        self.text1=Entry(self.panel2)
        self.text1.grid()
        self.text1.bind('<KeyPress>', self.keybind1)
        self.text1.focus()

    def keybind1 (self,event):
        if event.int in np.linspace(0,9,10):
            print event.int


root1=Tk()
window2(root1)
root1.mainloop()

我不断收到错误消息,指出事件实例没有属性int".我应该怎么办?

I keep getting error message that Event instance has no attribute 'int'. What should I do?

推荐答案

这使用 validatecommandtk.Entry 中的有效用户输入限制为可以解释的字符串作为浮动:

This uses validatecommand to restrict valid user input in the tk.Entry to strings which can be interpreted as floats:

import tkinter as tk

class window2:
    def __init__(self, master1):
        self.panel2 = tk.Frame(master1)
        self.panel2.grid()
        self.button2 = tk.Button(self.panel2, text = "Quit", command = self.panel2.quit)
        self.button2.grid()
        vcmd = (master1.register(self.validate),
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.text1 = tk.Entry(self.panel2, validate = 'key', validatecommand = vcmd)
        self.text1.grid()
        self.text1.focus()

    def validate(self, action, index, value_if_allowed,
                       prior_value, text, validation_type, trigger_type, widget_name):
        if value_if_allowed:
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False

root1 = tk.Tk()
window2(root1)
root1.mainloop()

参考文献:

  • Tk 手册页 解释了validatevalidatecommand选项.(感谢 schlenk 提供链接).
  • 我在此处学习了如何使用 Python 执行此操作.
  • The Tk man page explains the validate and validatecommand options. (Thanks to schlenk for the link).
  • I learned how to do this in Python here.

这篇关于限制 Tkinter Entry 小部件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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