[Tutor] Tkinter Q's

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Wed Jul 13 00:46:28 CEST 2005

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

> Hi first off, here's my code:
> # -*- coding: utf-8 -*-
> from Tkinter import *
> import random
> import time
> import about
> import quotes
> def closeprog():
>  raise SystemExit
> class main:
>  root = Tk()
>  frame = Frame()
>  root.title("Quoter %s" % (about.ver))
>  root.minsize(300, 50)
>  showquote = Label(root, text=random.choice(quotes.quote))
>  showquote.pack()
>  exit = Button(root, text="Exit", command=closeprog)
>  exit.pack(side=LEFT)
>  aboutprg = Button(root, text="About", command=about.main)
>  aboutprg.pack(side=LEFT)
>  totalq = Label(root, text=quotes.qts)
>  totalq.pack(side=BOTTOM)
>  root.mainloop()
> (I'd appreciate some suggestions, or notifications on how bad something
> is)

Some comments ---

You create a Frame, but you never use it.

You've put a whole lot of code in a class, but it's not in a class method.  This
is kinda missing the point of using classes in the first place (and it just
flat-out wouldn't work in the majority of OO languages).

Here's what I would do:

class Main(Frame):
    def __init__(self, master=None, **kw):
        Frame.__init__(self, master, **kw)

        showquote = Label(self, text=random.choice(quotes.quote))

        # etc

if __name__ == '__main__':
    root = Tk()
    main = Main(root)
    main.pack(fill=BOTH, expand=True)

Do you see what I am doing there, and why it is different from your approach?

> I have a small problem: I don't know how to make a button that would 
> redisplay another quote in the same window, ie I need a button that 
> says: Show Another Quote. (Actually I don't know how to make it show 
> another quote even in a new window!!). I got the interface from Catfood

Once you've got a label, you can change its text attribute by using its
.config() method.

So, you could do something like this:

    # ...
    showquote = Label(self, text=random.choice(quotes.quote))

    def changeQuote():
        currQuote = showquote.cget('config')  # Get the current quote
        newQuote = random.choice(quotes.quote)
        while newQuote == currQuote:          # Make sure the new quote differs
            newQuote = random.choice(quotes.quote)
    Button(self, text='Show another quote', command=changeQuote).pack()


More information about the Tutor mailing list