0

I would like a label that updates when I push a button. The label is a formated string that prints some attributes of an object.

This is what I tried. It displays properly but won't update.

from class_mnoply import *
from tkinter import *

Player1=Player("Hat")
message=str('''
____________________   

{0}
Bank account: ${1}
Dice1: {2}
Dice2: {3}


____________________    
    '''.format(Player1.name, Player1.bank, Player1.dice1, Player1.dice2))



mainWin = Tk()
topFrame=Frame(mainWin)
topFrame.pack(side=TOP)
button1 Button(mainWin,text="ThrowDice",fg="red",command=Player1.rollDice())
button1.pack(side=BOTTOM)
plLabel = Label(mainWin, textvariable=message)
plLabel.pack()
mainWin.mainloop()

1 Answers1

0

You have 1 typo in the following statement and 1 potential error:

button1 Button(mainWin,text="ThrowDice",fg="red",command=Player1.rollDice())

Can you guess what is the typo? If no, you are just missing the = sign.

On the other hand, you are assigning the return value of Player1.rollDice() to command, but this is not what you want. What you want is just set the Player1.rollDice method as the command that is called when button1 is pressed. Here's the correct syntax (note the absence at the end of ()):

button1 = Button(mainWin,text="ThrowDice",fg="red",command=Player1.rollDice)

Then, where is message defined in the following statement:

plLabel = Label(mainWin, textvariable=message)

There's no need to use a StringVar object, but if you want, you have first to declare it:

message = StringVar()

and finally you can use it as textvariable for your label.

Assuming you don't know what lambda is, this is a working example of what you are trying to do (without using a StringVar variable):

from tkinter import *


def set_label_text():
    plLabel.config(text='Hello World!')

mainWin = Tk()

topFrame=Frame(mainWin)
topFrame.pack(side=TOP)
button1 =Button(mainWin,text="ThrowDice",fg="red",
                command=set_label_text) # note the absence of ()
button1.pack(side=BOTTOM)
plLabel = Label(mainWin)
plLabel.pack()

mainWin.mainloop()
nbro
  • 15,395
  • 32
  • 113
  • 196
  • Maybe I need to be more clear. I get it to display properly, but what i want is for my fomat options for "message" to be updated when i click the button. When i call the function rollDice it sets new values to Player.dice1 and Player.dice2. I get the initial values (1) displayed, but when rollDice is called they both still show one. – user274132 Jan 18 '15 at 19:32
  • Here: `button1 Button(mainWin,text="ThrowDice",fg="red",command=Player1.rollDice())`, remove `()`, because you want not to assign the return value of `Player1.rollDice()` to `command`, but you just want to associate `Player.rollDice` method address to the command, and not actually the returned value of it, as I said before. – nbro Jan 18 '15 at 19:39
  • @user274132 See my comment above and my edited answer, if it's what you want – nbro Jan 18 '15 at 19:46