elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [Python] Tkinter básico - eventos
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Python] Tkinter básico - eventos  (Leído 6,572 veces)
Mitgus

Desconectado Desconectado

Mensajes: 63


Programming Lover


Ver Perfil
[Python] Tkinter básico - eventos
« en: 18 Junio 2013, 17:00 pm »

Hola compañeros. Soy novato en Python, me parece un lenguaje interesante por lo que estoy aprendiendo a programar con él.

Ayer empecé con Tkinter, y todo bien, lo único que no logro es hacer que un botón llame a una función para que muestre un resultado.

Código
  1. from tkinter import *
  2.  
  3. def operar(operacion):
  4.    if(operacion == "suma"):
  5.        print(operacion)
  6.        lbl = Label(root,text="Total: "+str(a.get()+b.get()))
  7.        lbl.grid(row=3,column=0)
  8.    elif (operacion == "resta"):
  9.        print(operacion)
  10.        lbl = Label(root,text="Total: "+str(a.get()-b.get()))
  11.        lbl.grid(row=3,column=0)
  12.  
  13. root = Tk()
  14. a = IntVar()
  15. b = IntVar()
  16. txtA = Entry(root, textvariable=a, width=15)
  17. txtB = Entry(root, textvariable=b, width=15)
  18. btnSumar = Button(root, text="Sumar", command=operar("resta"), width=15)
  19. txtA.grid(row=0,column=0)
  20. txtB.grid(row=1,column=0)
  21. btnSumar.grid(row=2,column=0)
  22. root.mainloop()
  23.  


Lo que quiero hacer es algo así (Java):

Código
  1. public class Hola {
  2.  
  3. void calcula(String operacion)
  4. {
  5.   int numero1 = Integer.parseInt(textbox1.getText());
  6.   int numero2 = Integer.parseInt(textbox2.getText());
  7.  
  8.   if(operacion.equals("suma") {
  9.    labelResultado.setText(String.valueOf(numero1+numero2));
  10.   else if (operacion.equals("resta") {
  11.    labelResultado.setText(String.valueOf(numero1-numero2));
  12.    // así con multiplicación y división
  13.  
  14.  }
  15.  
  16. // evento del boton
  17. public void actionPerformed(ActionEvent evento)
  18. {
  19.   Objet item = (String) combobox.getSelectedItem();
  20.   calcula(item)
  21.  }
  22.  

Cuando corro el programa, llama explícitamente a la función operar, si que haya presionado el botón. Esto sale por la terminal al ejecutar el script:

Código
  1. >>>
  2. resta
  3. >>>
  4.  


¿Algún entendido que pueda ayudarme?

Gracias.


« Última modificación: 18 Junio 2013, 20:25 pm por Migugami » En línea

Linux User #560388
Mitgus

Desconectado Desconectado

Mensajes: 63


Programming Lover


Ver Perfil
Re: [Python] Tkinter básico - eventos
« Respuesta #1 en: 18 Junio 2013, 23:34 pm »

Bueno, ya lo solucioné.

La cosa era con un lamba, de este modo:

Código
  1. boton = Button(root, text="Calcular",command=lambda: operar("parametro"), width=15)
  2.  

Minicalculadora por si a algún novato como yo le sirve.. Encontrar info de tkinter actual solo se encuentra en inglés xD

Código
  1. from tkinter import * #importa el modulo grafico
  2. from tkinter import ttk # importa elementos (widgets)
  3. from tkinter import messagebox #importa messagebox
  4.  
  5. def operar():
  6.    error = False # sera el control de la operacion
  7.    texto = str(combo.get()) # extraemos el item seleccionado
  8.  
  9.    # de acuerdo a la opcion escogia, se realiza una operacion
  10.    if(texto == "Sumar"):
  11.        lbl = Label(root,text="Total: "+str(a.get()+b.get()))
  12.    elif(texto == "Restar"):
  13.        lbl = Label(root,text="Total: "+str(a.get()-b.get()))
  14.    elif(texto=="Multiplicar"):
  15.        lbl = Label(root,text="Total: "+str(a.get() * b.get()))
  16.    # hacemos un try - catch (si se divide entre 0)
  17.    else:
  18.        try:
  19.            lbl = Label(root,text="Total: "+str(round(a.get() / b.get(),2)))
  20.        except:
  21.            messagebox.showerror("Error","No es posible la división entre 0")
  22.            error = True # avisamos que hay error
  23.    # si no hay error, se muestra el resultado
  24.    if(error==False):
  25.        lbl.grid(row=4,column=0)
  26.  
  27.  
  28. root = Tk() #crea la ventana
  29. a = DoubleVar() #maneja el tipo de dato que se usara
  30. b = DoubleVar()
  31. txtA = Entry(root, textvariable=a, width=15) #configuramos los textbox
  32. txtB = Entry(root, textvariable=b, width=15)
  33. # agregamos elementos al combo
  34. combo = ttk.Combobox(root,value=('Sumar','Restar','Multiplicar','Dividir'), takefocus=0)
  35. combo.grid(row=3,column=0)
  36. # creamos el boton y configuramos su accion (command = 'funcion')
  37. btnSumar = Button(root, text="Calcular", command=operar, width=15)
  38. txtA.grid(row=0,column=0)
  39. txtB.grid(row=1,column=0)
  40. btnSumar.grid(row=2,column=0)
  41. root.mainloop() #maneja todo lo que ocurre
  42.  


En línea

Linux User #560388
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Weather tkinter (Python)
Scripting
@synthesize 1 3,471 Último mensaje 9 Marzo 2011, 17:20 pm
por Marot77
[Python] Cliente Ftp Tkinter
Scripting
Runex 4 3,969 Último mensaje 18 Abril 2012, 14:51 pm
por Runex
Ayuda con Python, ftp y Tkinter
Scripting
Eirthur 1 3,958 Último mensaje 11 Mayo 2013, 03:56 am
por daryo
[Python/Tkinter](Kyurem v2.0)Consola de comandos hecha en python
Scripting
AdeLax 0 4,260 Último mensaje 9 Agosto 2013, 22:45 pm
por AdeLax
[Python/Tkinter](Kyurem v2.0)Consola de comandos hecha en python (Continuación)
Scripting
Príncipe_Azul 5 4,912 Último mensaje 16 Abril 2014, 11:19 am
por AdeLax
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines