Matt
Matt

Reputation: 13

How to change values into functions using Buttons in Python 3.4

I'm trying to change 'number' in a function called from a Tkinter Button as in function2 below. function1 recognizes 'number' and works fine, function2 gives an UnboundLocalError. If I try to pass the value in the Button(like: command=function2(number)) the function is executed immediately without pressing the button. Can someone help?

from tkinter import *

def function1():
    print('In pcomm.')
    print('number=', str(number))

def function2():
    print('In acomm.')
    print('number=', str(number))
    number += 1  #UnboundLocalError: local variable 'number' referenced before assignment
    print('number=', str(number))

#create the window
root = Tk()

number = 2
print('Just assigned: number=', str(number))

printButton = Button(root, text = "Press to print.", command = function1).grid()
addButton = Button(root, text = "Press for number+=1.", command = function2).grid()


#kick off the event loop
root.mainloop()

Upvotes: 0

Views: 104

Answers (1)

mgilson
mgilson

Reputation: 309909

To avoid the global, you'd want to use a class.

class AppData(object):
    def __init__(self):
        self.number = 2

    def function1(self):
        print('In pcomm.')
        print('number=', str(self.number))

    def function2(self):
        print('In acomm.')
        print('number=', str(self.number))
        self.number += 1
        print('number=', str(self.number))

You would then create an instance of the class, and pass it's bound methods to the buttons...

app = AppData()
addButton = Button(root, text = "Press for number+=1.", command = app.function2)
addButton.grid()

Note that you'll frequently see the button as part of another (or the same) class.

Upvotes: 1

Related Questions