简体   繁体   中英

Instance attribute of an object from a class inherited from frame, how to check the type of the widget

my code is :

from tkinter import *

class Inter(Frame):

    def __init__(self, fenetre, **kwargs):
        Frame.__init__(self, window, width=768, height=576, **kwargs)
        self.pack(fill=BOTH)
        self.compt= 0

        self.message = Label(self, text="No click")
        self.message.pack()

        self.button_quit = Button(self, text="Quit", command=self.quit)
        self.button_quit.pack(side="left")

        self.button_click = Button(self, text="Click", fg="red",
                command=self.click)
        self.button_click.pack(side="right")

    def click(self):

        self.compt += 1
        self.message["text"] = " number of clicks={}".format(self.compt)

I have created the object

top= Tk()
interface = Inter(top)

interface.mainloop()
interface.destroy()

I have tried vars() and __dict__ methods, but I get the instance attributes(ie name of the widgets) of the object 'interface' as str. So I can't check if the widget is a button or a label, using .winfo_class( method.

You can simply compare the object type, like you can with any other python object:

>>> isinstance(self.button_click, Tkinter.Button)
True

The method you are looking for is winfo_children .

winfo_children()

Returns a list containing widget instances for all children of this widget. The windows are returned in stacking order from bottom to top. If the order doesn't matter, you can get the same information from the children widget attribute (it's a dictionary mapping Tk widget names to widget instances, so widget.children.values() gives you a list of instances).

syntax : root.winfo_children()

if you want to check classes for children in interface

for name in interface.children:

    widget = interface.nametowidget(name)

    print(name, 'is Button:', isinstance(widget, tkinter.Button))
    print(name, 'is Label:',  isinstance(widget, tkinter.Label))

    print(name, 'is Button:', widget.winfo_class() == "Button")
    print(name, 'is Label:',  widget.winfo_class() == "Label")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM