Home > front end >  Tkinter updating labels
Tkinter updating labels

Time:02-18

I tried to make a GUI for a weather API application, and I want it so, that when I request a temperature, the next temperature is replacing the further Label (temperature)

This is what I wrote

import requests
from tkinter import *

global stadt

TOKEN = "-----------------"
a = "jaaa"

root = Tk()

root.title("Wetter")
root.geometry("300x150")

def get_entry():
    stadt = Entry1.get()
    url = f"https://api.openweathermap.org/data/2.5/weather?q={stadt}&appid={TOKEN}"
    f = requests.get(url).json()

    temperatur = f["main"]["temp"]
    temperatur = temperatur - 273.15
    luftdruck = f["main"]["pressure"]

    alltext= f"Die Temperatur in {stadt} beträgt {round(temperatur)}°C\nDer Luftdruck in {stadt} beträgt {luftdruck}Ba"

    Label3 = Label(root)
    Label3.config(text=alltext)
    Label3.pack()

    

Label1 = Label(root, text="Bitte Stadt eingeben")
Label1.pack()

Entry1 = Entry(root)
Entry1.pack()



Button1 = Button(root, text="Senden", command=get_entry)
Button1.pack()

root.mainloop()

and I want to know I can update a Label without create a new one

CodePudding user response:

You can use tk.label.configure method. Here's an example:

import tkinter as tk

class Test():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(self.root, text="Text")

        self.button = tk.Button(self.root,
                                text="Click to change text below",
                                command=self.changeText)
        self.button.pack()
        self.label.pack()
        self.root.mainloop()

    def changeText(self):
        self.label.configure(text="Text Updated")        
app=Test()

You can also change other label params

CodePudding user response:

You can use the ["text"] variable to change , for example:

from tkinter import *

root = Tk()

Label1 = Label(root, text = "Something")
Label1.pack()

def change_label():
    Label1["text"] = "Something else"

ChangeButton = Button(text="Change", command = change_label)
ChangeButton.pack()

root.mainloop()
  • Related