获取Python Tkinter对象类型 [英] Getting Python Tkinter Object Type

查看:94
本文介绍了获取Python Tkinter对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个程序,该程序可以处理Python程序中许多不同的输入小部件。

I am currently working on a program which handles a number of different possible entry widgets in a Python program.

我需要一些代码才能确定哪种类型小部件的特定对象,例如 Entry Checkbutton

I need some code to be able to determine what type of widget a particular object is, for example Entry or Checkbutton.

我尝试使用 type(var)方法无济于事(我收到了缺少必需变量 self )以及 var .__ class __ ,但我没有任何进展。

I have tried using the type(var) method to no avail (I get the error missing required variable self) as well as the var.__class__ and I am making no progress.

for d in dataTypes:
    if isinstance(d, Entry):
        print("Found Entry!")
    elif type(d).__name__ == 'Checkbutton':
        print("Found Checkbox!")

有人对我怎么做有任何想法解决方案?

Does anyone have any idea of how I can solve this?

推荐答案

如果需要使用名称作为字符串,则可以使用 .winfo_class( )方法:

If you need the name as a string, you can use the .winfo_class() method:

for d in dataTypes:
    if d.winfo_class() == 'Entry':
        print("Found Entry!")
    elif d.winfo_class() == 'Checkbutton':
        print("Found Checkbutton!")

或者,您可以访问 __ name __ 属性:

Or, you could access the __name__ attribute:

for d in dataTypes:
    if d.__name__ == 'Entry':
        print("Found Entry!")
    elif d.__name__ == 'Checkbutton':
        print("Found Checkbutton!")

也就是说,使用 isinstance 是更常见的/ pythonic方法:

That said, using isinstance is a more common/pythonic approach:

for d in dataTypes:
    if isinstance(d, Entry):
        print("Found Entry!")
    elif isinstance(d, Checkbutton):
        print("Found Checkbutton!")

此外,您的当前代码失败,因为 type(d).__ name __ 不返回您认为它会做什么:

Also, your current code is failing because type(d).__name__ does not return what you think it does:

>>> from tkinter import Checkbutton
>>> type(Checkbutton).__name__
'type'
>>>

注意,它返回由 type返回的类型对象的名称,而不是 Checkbutton 的名称。

Notice that it returns the name of the type object returned by type, not the name of Checkbutton.

这篇关于获取Python Tkinter对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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