0

我目前正在学习 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:name 'entry' is not defined”我试图改变事情的顺序,但总是有这些错误之一..它指向我做的行.register() 东西

--EDITED CODE-- 这不会给我一个错误,但仍然允许我删除......

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 >> mainframe >> entry。它必须是 root、大型机还是两者都可以?)

4

1 回答 1

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。使用类的好处之一是它允许您在文件中比使用它们的位置更远地定义方法。通过使用程序样式,您必须在使用函数之前定义函数*。

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

于 2014-01-04T16:52:22.597 回答