Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching Tkinter child widgets (winfo_children) to determine type

I'm trying to automatically clear all Entry widgets in a parent widget.

import Tkinter
import re
root=Tkinter.Tk()

E1=Tkinter.Entry(root)
E1.pack()

E2=Tkinter.Entry(root)
E2.pack()

L1=Tkinter.Label(root,text='Label1')
L1.pack()

I'm running into 3 problems

  1. While I can find out the children widget type, I can't seem to be able to use it in a pattern match. Printing out the wlist[0] below is different from the shell output?

Eg:

>> wlist=root.winfo_children()
>> wlist
[<Tkinter.Entry instance at 0x00000000151911C8>,
 <Tkinter.Entry instance at 0x00000000151BAD88>,
 <Tkinter.Label instance at 0x00000000151B29C8>]

>> wlist[0]    # shell output
<Tkinter.Entry instance at 0x00000000151911C8>

>> print wlist[0]   # print output here is different vs shell output above
.353964488L
  1. I think due to the differences between the print output & shell output above, my pattern match can't work?

Eg

>> re.search(r'Entry',wlist[0])
    << No output >>
  1. Assuming one is able to determine via pattern match that a child widget is indeed an Entry widget, how would you get the widget object itself to perform a delete method call?

Eg:

## Assuming I have a function to to clear the entry
## How would I pass the object from the pattern match in #2 to this function?
def clear_entry(objEntry):
    objEntry.delete(0,Tkinter.END)
like image 324
J.Wong Avatar asked Dec 09 '22 00:12

J.Wong


1 Answers

The items returned from winfo_children() is a list of widgets. Tkinter widgets have a method to tell you the underlying widget class: winfo_class.

>>> wlist[0].winfo_class()
'Entry'

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

>>> isinstance(wlist[0], Tkinter.Entry)
True

Since the result of winfo_children is a list of widgets, you can iterate over them and clear out all of the entry widgets like this:

for widget in root.winfo_children():
    if isinstance(widget, Tkinter.Entry):
        widget.delete(0, "end")
like image 88
Bryan Oakley Avatar answered Jan 22 '23 18:01

Bryan Oakley