[Tutor] problem with msg widget & button

Peter Otten __peter__ at web.de
Tue Nov 29 16:19:55 CET 2011


Cranky Frankie wrote:

> OK, I've stripped out all the comments and put it here:
> 
> http://www.pastie.org/2938751
> 
> 
> This works but the button doesn't put the next comment in the window.
> The only way I could figure to get the next comment in the window is
> to add the msg_widget line to the disp_quote function, but when I do
> that, it puts out *another* msg-widget! That is not what I want at
> all. I just want the next quote button to put the next quote in the
> box.

Hm, your description doesn't match with the code you posted which only 
creates one Message.

Also you still initialize the command parameter with the function result

Button(..., command=f()) # wrong

instead of the function itself

Button(..., command=f) # correct.

Here's a fixed version:


#!/usr/bin/python3

import random                              
from tkinter import *                       

quote_dict = {
1:["Kahlil Gibran", "A candle loses nothing of its light when lighting 
another."],
# ...
}

def choose_quote():
    rand_quote = (random.randrange(len(quote_dict))+1)          
    quote = quote_dict[rand_quote][1]                
    author = quote_dict[rand_quote][0]       
    return (quote+"\n\n"+author)       

def display_quote():
    msg_widget["text"] = choose_quote()

root = Tk()                                    
win = Frame()                                   
win.pack()                                     

label_widget = Label(win, text="Welcome to Quote of the Day")   
label_widget.pack(side = TOP, expand=YES, fill=BOTH)           

msg_widget = Message(
    win, anchor=NW, justify=LEFT, width=1000, bd=2,
    bg="white", relief=SOLID, text=choose_quote())
msg_widget.pack()                               

next_button = Button(win, text="Next Quote", command=display_quote) 
next_button.pack(side=LEFT)

quit_button = Button(win, text="QUIT", fg="red", command=quit) 
quit_button.pack(side=RIGHT)

root.mainloop()                    




More information about the Tutor mailing list