Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

class - Getting Python Tkinter Object Type

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!")

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!")

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!")

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'
>>>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...