【问题标题】:Entry Validation going wrong with tkintertkinter 的条目验证出错
【发布时间】:2017-09-01 02:57:04
【问题描述】:

我目前正在学习 tkinter 基础知识,并且正在构建一个小型、超级简单的程序来测试我对一些最基本的小部件的了解。

我在验证和条目方面遇到问题,可能是因为我对此事缺乏了解......这提出了三个问题:

1 - 如何做这里所做的事情:https://stackoverflow.com/a/4140988/2828287 没有类部分。只在脚本运行时执行。

2 - 那些自我是什么。和 .self 在那里做什么?哪些是因为那是一个类,哪些是因为验证方法本身??

3 - 我的代码有什么问题?基于这个解释>>http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html

from tkinter import *
from tkinter import ttk

# function that should take the '%d' replacer and only validate if the user didn't delete
def isOkay(self, why):
    if why == 0:
        return False
    else:
        return True

okay = entry.register(isOkay) # didn't understand why I had to do this, but did it anyway...
entry = ttk.Entry(mainframe, validate="key", validatecommand=(okay, '%d'))
# the mainframe above is a ttk.Frame that contains all the widgets, and is the only child of the usual root [ = Tk()]
entry.grid(column=1,row=10) # already have lots of stuff on upper rows

我得到的错误是这样的: “NameError:名称‘条目’未定义” 我试图改变事情的顺序,但总是有这些错误之一。它指向我做 .register() 东西的那一行

--编辑后的代码-- 这不会给我一个错误,但仍然允许我删除...

def isOkay(why):
    if (why == 0):
        return False
    else:
        return True

okay = (**root**.register(isOkay), "%d")
entry = ttk.Entry(mainframe, validate="key", validatecommand=okay)
entry.grid(column=1,row=10)

(“根”部分写在 ** ** 之间,它必须是根吗?或者它可以是要使用它的小部件的任何父级?或者它必须是直接父级呢? 例如,我有: 根>>主机>>条目。它必须是 root、大型机还是两者都可以?)

【问题讨论】:

    标签: python-3.x validation tkinter tkinter-entry


    【解决方案1】:

    self 的所有用法都是由于使用了类。它们与验证完全无关。什么都没有。

    这是一个没有使用类的例子,也没有描述验证函数的长注释:

    import Tkinter as tk
    
    def OnValidate(d, i, P, s, S, v, V, W):
        print "OnValidate:"
        print "d='%s'" % d
        print "i='%s'" % i
        print "P='%s'" % P
        print "s='%s'" % s
        print "S='%s'" % S
        print "v='%s'" % v
        print "V='%s'" % V
        print "W='%s'" % W
        # only allow if the string is lowercase
        return (S.lower() == S)
    
    root = tk.Tk()
    
    vcmd = (root.register(OnValidate), 
            '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
    entry = tk.Entry(root, validate="key", 
                          validatecommand=vcmd)
    entry.pack()
    root.mainloop()
    

    注意:注册命令的目的是在底层 tcl/tk 引擎和 python 库之间建立一座桥梁。本质上,它创建了一个调用OnValidate 函数的tcl 命令,并为其提供了提供的参数。这是必要的,因为 tkinter 未能为 tk 的输入验证功能提供合适的接口。如果您不想要所有花哨的变量(%d%i 等),则无需执行此步骤。

    错误NameError: name 'entry' is not defined 是因为您在定义entry 是什么之前使用了entry。使用类的好处之一是它允许您在文件中比使用它们的位置更远地定义方法。通过使用程序样式,您必须在使用函数之前对其进行定义*。

    * 从技术上讲,您总是必须在使用函数之前定义它们。在使用类的情况下,在创建类的实例之前,您实际上不会使用类的方法。直到非常接近文件末尾时才会真正创建实例,这样您就可以在使用代码之前定义代码。

    【讨论】:

    • 好的,明白了……虽然我还没有掌握课程……你能看看我要编辑的代码,看看吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多