Uso de variable Global

C

craf

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()


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?.

Saludos.

Cristian
 
P

Peter Otten

craf said:
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()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top