faqts : Computers : Programming : Languages : Python : Tkinter

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 6 people (67%) answered Yes
Recently 4 of 6 people (67%) answered Yes

Entry

How do you make the original text in a Label change randomly using a button?

Aug 15th, 2002 05:32
Jørgen Cederberg, chester willis,


Hi,

you could do it with following sourcecode. Note that I used a StringVar 
to update the Label text. This is an easy way to do it. Otherwise you 
would have to use a configure call on the Label widget.


from Tkinter import *
import random

mylist = ['why not?',
          'don''t ask!',
          'it''s your karma.',
          'stupid question!',
          'how should I know?',
          'can you rephrase that?',
          'it should be obvious.',
          'the devil made me do it.',
          'the computer did it.',
          'the customer is always right.',
          'in the beginning, God created the heavens and the earth...',
          'don''t you have something better to do?']


class RandomLabel:
    def __init__(self, root, randlist):
        self.root = root
        self.randlist = randlist
        self.label = StringVar() 
        self.makeWidgets()    
        
    def makeWidgets(self):     
        Button(self.root,
               text='Why...',
               command=self.setlabel).pack(side=LEFT)        
        Label(self.root,
              textvariable=self.label).pack(side=LEFT)               
        
    def setlabel(self):
        self.label.set(random.choice(self.randlist))        
        
        
if __name__ == '__main__':
    root = Tk()
    RandomLabel(root, mylist)
    root.mainloop()