[Tutor] Tkinter Q's

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Thu Jul 14 00:54:16 CEST 2005


Quoting Joseph Quigley <cpu.crazy at gmail.com>:

> Hi, 
> 	what's the **kw stand for, used for? What does it mean?

Sorry about that.  A couple of people have already answered; I'll just give you
a couple of examples which might help you understand:

>>> def showArgs(**kw):
...  print kw
...
>>> showArgs(foo=1, bar=2, string='My string')
{'foo': 1, 'bar': 2, 'string': 'My string'}

Basically, **kw means "Take any keyword arguments that were unused, and put them
in a dictionary called 'kw'".

Here's another example:

>>> def myFunction(x=1, y=2, **kw):
...  print "x == %s, y == %s" % (x, y)
...  print "Unused arguments:", kw
...
>>> myFunction(a='foo', b='bar', y=8, c='baz', x=13)
x == 13, y == 8
Unused arguments: {'a': 'foo', 'c': 'baz', 'b': 'bar'}

Some of the keyword arguments are given explicit names, to make them easy to
access.  The remainder are available still in kw.

You can also do the reverse:

>>> def doSomeMaths(x=3, y=2, z=8):
...  return (x+y)*z
...
>>> kwargs = { 'x':4, 'y':3, 'z':2 }
>>> doSomeMaths(**kwargs)
14

In this case, the dictionary 'args' is expanded into three keyword parameters:
x=4, y=3, z=2

You can also do the same thing with positional parameters; in this case you just
use one *.

Does that help?

> Uh, not really, no. I'm very new to GUI. So you're saying that If I make
> the class actually do something (I edited and example in:
> An into to Tkinter, Fredrik Lundh).

Tkinter programming involves making Frames, Buttons, Labels, etc. and putting
them all together.  What I like to do is subclass Frame (or other things) to
make new GUI components, which I can then pack() into Frames as normal.

Here's a really basic example:

from Tkinter import *

class BlueLabel(Label):
 """ A Label with a blue background. """

 def __init__(self, *args, **kw):
    kw['background'] = 'blue'
    Label.__init__(self, *args, **kw)

if __name__ == '__main__':
    tk = Tk()
    l1 = Label(tk, text='This is a normal label.')
    l1.pack()
    l2 = BlueLabel(tk, text='This is a blue label.')
    l2.pack()
    tk.mainloop()

(and, this time, I have tested this code :-) Although you may need to fix up the
indentation a bit)

> > currQuote = showquote.cget('config') # Get the current quote

As Michael pointed out, this was a bug.  Sorry.

-- 
John.


More information about the Tutor mailing list