user6253656
user6253656

Reputation:

Plus 1 to variable with tkinter button

I'm very new in python, I'm trying give + 1 to "x" variable with tkinter button, can you help me figure out with it please

import tkinter as Tk

x = 0

root = Tk.Tk()

def add():

    x == (x + 1) # Here but seems wrong way 

Tk.Button(root, text='PLUS 1 to X', command=add,
        height=5, width=20,).pack(side=Tk.LEFT)

root.mainloop()

Upvotes: 0

Views: 811

Answers (2)

Anuj
Anuj

Reputation: 23

You are using comparison operator (==) in place of assignment operator(=)

Corrected version

from tkinter import *
>>> root = Tk()
>>> def add():
...     global x
...     x += 1
...     messagebox.showinfo(message=x)
... 
>>> from tkinter import messagebox
>>> x = 0
>>> adder = Button(root, text='ADD 1 TO X', command=add)
>>> adder.grid()

Upvotes: 1

McClamrock
McClamrock

Reputation: 927

I'm not seeing where the value of x is supposed to be displayed, and I'm not seeing how the successive values of x are supposed to be retained, in your code. Here's one simple way to do it:

>>> from tkinter import *
>>> root = Tk()
>>> def add():
...     global x
...     x += 1
...     messagebox.showinfo(message=x)
... 
>>> from tkinter import messagebox
>>> x = 0
>>> adder = Button(root, text='ADD 1 TO X', command=add)
>>> adder.grid()

Setting x as a global variable allows you to change it within the function and keep the change after the function returns. As you probably know, x += 1 means the same as x = x+1, i.e., the new value of x is 1 more than the old value.

Upvotes: 1

Related Questions