PyRoss
PyRoss

Reputation: 129

Python 3.3 (tkinter): Value does not change

First problem is that when i click '+ $16' button it doesn't show the increase, although you can see it after closing the window and typing money into Python Shell. Second problem is that after I added those sticky=SE and sticky=SW window won't appear at all (without error messages).

# money adder
import sys
from tkinter import *
import random

root = Tk()
root.geometry('360x160+800+200')
root.title('app')

money = 100

def addMoney():
    global money
    money = money + 16

def end():
    global root
    root.destroy()

appTitle = Label(root,text='Money Adder',font='Verdana 31',fg='lightblue').pack()
budget = Label(root,text='Budget: $'+str(money),font='Arial 21',fg='green').pack()
moneyButton = Button(root,text='+ $16',width=17,height=2,command=addMoney).grid(sticky=SW)
endButton = Button(root,text='Quit',width=5,height=2,command=end).grid(sticky=SE)

root.mainloop()

Upvotes: 0

Views: 484

Answers (2)

A. Rodas
A. Rodas

Reputation: 20679

First of all, you are storing the return value of grid or pack, which is always None, instead of the reference to the widgets. Besides, you shouldn't use both geometry managers at the same time (if you are new to Tkinter, I'd suggest grid instead of pack).

To update the text of the widget, you have to use config with the text keyword or budget['text']:

budget = Label(root,text='Budget: $'+str(money),font='Arial 21',fg='green')
budget.pack()

def addMoney():
    global money
    money += 16
    budget.config(text='Budget: $'+str(money))

moneyButton = Button(root,text='+ $16',width=17,height=2,command=addMoney)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124100

You store a new string based on the money variable in the budget Label; the label doesn't keep a reference to the money variable for you.

Simply set the label value each time you call your addMoney function:

def addMoney():
    global money
    money = money + 16
    budget.set('$' + str(money))

Upvotes: 1

Related Questions