Search code examples
python-3.xtkinterreturn-valuestickyappearance

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()

Solution

  • 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)