Adder with tkinter

2

Hello is my first question on this page, I hope not to make mistakes in the formulation of the same, well what happens is that I want to make an app that when click on a button, increase the value of a variable and appear in the text box of the window.

The problem is that I do not know how to take an integer variable, say n, that when you press the button add +1 to the value of the variable n and that it is stored in the variable n.

I hope the question was clear. I leave my code:

from tkinter import *
n=0
def sumar():
    global n
    n+=1
    e=str(n)
    produccion.set(e)     


raiz=Tk()
produccion=StringVar()
prod=Entry(raiz,textvariable=produccion)
prod.pack(side=TOP)
contador=ttk.Button(raiz,text="sumador",command=sumar())
contador.pack(side=BOTTOM)
raiz.mainloop() 
    
asked by Camilo Martinez 21.03.2018 в 00:17
source

1 answer

0

It is a fairly common error, at command a reference to the function / method to be executed is passed when the button is pressed, you are passing it back as you do command=sumar() . With sumar() you're calling the function so the argument command you pass None (which is what returns sumar ). It should be command=sumar , note the lack of parentheses.

You can do without the global variable n if you want it at the cost of a casting to int . On the other hand, from modulo import * is generally considered a bad practice in Python, makes the readability of the code difficult, you can overlap names of one import with another without realizing it (with the consequent errors) and the current namespace is unnecessarily populated. As the Python zen says:

  

"Explicit is better than implied".

import tkinter as tk
from tkinter import ttk


def sumar():
    produccion.set(str(int(produccion.get()) + 1))     


raiz = tk.Tk()
produccion = tk.StringVar(raiz, "0")
prod = tk.Entry(raiz, textvariable=produccion)
prod.pack(side=tk.TOP)
contador = ttk.Button(raiz, text="sumador", command=sumar)
contador.pack(side=tk.BOTTOM)

raiz.mainloop() 
    
answered by 21.03.2018 / 01:15
source