Uso de variable Global

Peter Otten __peter__ at web.de
Thu Dec 2 17:06:25 EST 2010


craf wrote:

> Hola.
> 
> 
> Estoy probando Tkinter y escribí este pequeño código el cual crea un
> formulario con un textbox y un botón. Al ingresar un dato en el textbox
> y presionar el botón, se imprime en la consola el valor.
> 
> 
> ---CODE--------------------
> 
> from Tkinter import *
> 
> def muestra():
>     print(valor.get())
> 
> class App:
>     def __init__(self,master):
>         global valor
>         valor = StringVar()
>         e = Entry(master,textvariable=valor).pack()
>         b = Button(master,text='Mostrar',command=muestra).pack()

pack() returns None so both e and b set to None here. In this case it 
doesn't matter because you don't do anything with e and b.

> master = Tk()
> app = App(master)
> master.mainloop()
> 
> -----------------------------
> 
> Funciona, pero tuve que hacer uso de una variable Global.
> 
> Pregunta: ¿Es valida esta forma?, ¿Se puede hacer de otra forma, sin
> ocuparla?.

I'd prefer to make valor an attribute and muestra() a method:

from Tkinter import *     

class App:
    def __init__(self, master):
        self.valor = StringVar()
        Entry(master, textvariable=self.valor).pack()
        Button(master, text='Mostrar', command=self.muestra).pack()
    def muestra(self):
        print self.valor.get()

master = Tk()
app = App(master)
master.mainloop()




More information about the Python-list mailing list