Change value of a label dynamically

1

I'm a beginner in Python. How do I change the value of a label dynamically?

To be more specific, I have the following code:

#!/usr/bin/env python
from Tkinter import *
import socket, webbrowser

root = Tk()
root.title("Test - waghcwb")

def window(w=300, h=200):
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))
window(270, 100)

def Open():
    text_contents = text.get()
    url = str(socket.gethostbyname( text.get() ))

    if url != '0.0.0.0':
        webbrowser.open("http://%s" %url)
    else:
        #Erro para a label aqui
        print("Erro")

info = Label(root, text="Testando", pady=20).pack()

text = Entry(root, width=40).pack()

button = Button(root, text="Enviar", command=Open, width=40).pack()

error = Label(root, text="", pady=5)

root.mainloop()

Note the else: there, that's where I'd like to insert my error message.

My idea was to leave an empty label there and only enter data when there is an error, but as I said I'm a good beginner and I do not know any way to do that.

    
asked by anonymous 27.07.2014 / 09:33

2 answers

1

Notice this other example:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from Tkinter import *

# Funções...

def Cumprimente():
    hello.set("Olá, mundo!")

# Interface...

gui = Tk()
gui.title("Olá Mundo")
gui.geometry("400x400")

btn = Button(gui, text="Cumprimente", command=Cumprimente)
btn.pack()

hello = StringVar()
lbl = Label(gui, textvariable=hello)
lbl.pack()

gui.mainloop()

Label text does not receive values directly from Python, so you need to use the "StringVar" object ...

hello = StringVar()

Next, passing the text variable as a parameter to the Label object ...

lbl = Label(gui, textvariable=hello)

In this way, when my "Greet" function is called, it is not the Label that changes, but the "hello" object (StringVar) through the "set" method ...

def Cumprimente():
    hello.set("Olá, mundo!")

Save and run the example to see the thing in action.

    
31.07.2014 / 19:41
1

Hello wag could try as follows too:

import tkMessageBox

def Open():
text_contents = text.get()
url = str(socket.gethostbyname( text.get() ))

if url != '0.0.0.0':
    webbrowser.open("http://%s" %url)
else:
    #Erro para a label aqui
    tkMessageBox.showinfo("error", "erro a Url que você inseriu não existe")

I recommend giving a look at how to handle errors would be a good one.

link

    
16.08.2014 / 13:15