簡體   English   中英

如何更新 tkinter 中的文本標簽?

[英]How to update text Labels in tkinter?

每次單擊按鈕獲取天氣(我使用 Json 從網站獲取信息)時,以前的文本仍然存在,新文本會打印在它下面,但我希望更新舊文本。 我怎樣才能做到這一點? 請幫忙。

from tkinter import *
import requests
import json

root = Tk()
root.title("Weather")
root.geometry("600x400")

def RealWeather():

    try:
        api_request = requests.get("http://api.openweathermap.org/data/2.5/weather?appid=c2fc19de6fcd6869c4a9e167ee0f2eb7&q=" + city.get())
        api = json.loads(api_request.content)
        location = api['name'] + ", " + api['sys']['country']
        temp = int(api['main']['temp'] - 273.15)
        ws = api['wind']['speed']
        status = api['weather'][0]['main']

        Labelloc = Label(root, text="Location",background='#5182cf').grid(row=2,column=0)
        Label_loc = Label(root, text=location ,background='#5182cf').grid(row=2, column=1)

        Labeltemp = Label(root, text="Temperature",background='#5182cf').grid(row=3,column=0)
        Label_temp = Label(root, text=temp,background='#5182cf').grid(row=3,column=1)

        Labelws = Label(root, text="Wind Speed",background='#5182cf').grid(row=4,column=0)
        Label_ws = Label(root, text=ws,background='#5182cf').grid(row=4,column=1)

        Labelstatus = Label(root, text="Status",background='#5182cf').grid(row=5,column=0)
        Label_status = Label(root, text=status,background='#5182cf').grid(row=5,column=1)


    except Exception as e:
        api = "Error..."

    EmptyLabel = Label(root, text="", background='#5182cf').grid(row=1, column=0)


butn = Button(root, text="Search", command=RealWeather).grid(row=0, column=3)
Label1 = Label(root, text="Enter City: ").grid(row=0,column=0)
city = Entry(root)
city.grid(row=0, column=1, padx=20)

root.mainloop()

這就是我將如何繼續您的回答。 首先在 function 之外創建標簽並在單獨的行上使用grid() ,因此它們不是None

Labelloc = Label(root, text="Location",background='#5182cf')
Label_loc = Label(root)

Labeltemp = Label(root, text="Temperature",background='#5182cf')
Label_temp = Label(root)

Labelws = Label(root, text="Wind Speed",background='#5182cf')
Label_ws = Label(root)

Labelstatus = Label(root, text="Status",background='#5182cf')
Label_status = Label(root)

現在在 function 內部,每次運行 function 時,您都必須調用config()方法來更新 label:

Labelloc.grid(row=2,column=0) #grid it when the func is ran
Label_loc.config(text=location,background='#5182cf')
Label_loc.grid(row=2, column=1) #grid it when the func is ran

Labeltemp.grid(row=3,column=0) #grid it when the func is ran
Label_temp.config(background='#5182cf')
Label_temp.grid(row=3,column=1) #grid it when the func is ran

Labelws.grid(row=4,column=0) #grid it when the func is ran
Label_ws.config(text=ws,background='#5182cf')
Label_ws.grid(row=4,column=1) #grid it when the func is ran

Labelstatus.grid(row=5,column=0)
Label_status.config(text=status,background='#5182cf')
Label_status.grid(row=5,column=1)

所以最終代碼:

from tkinter import *
import requests
import json

root = Tk()
root.title("Weather")
root.geometry("600x400")

def RealWeather():

    try:
        api_request = requests.get("http://api.openweathermap.org/data/2.5/weather?appid=c2fc19de6fcd6869c4a9e167ee0f2eb7&q=" + city.get())
        api = json.loads(api_request.content)
        location = api['name'] + ", " + api['sys']['country']
        temp = int(api['main']['temp'] - 273.15)
        ws = api['wind']['speed']
        status = api['weather'][0]['main']

        Labelloc.grid(row=2,column=0)
        Label_loc.config(text=location,background='#5182cf')
        Label_loc.grid(row=2, column=1)

        Labeltemp.grid(row=3,column=0)
        Label_temp.config(background='#5182cf')
        Label_temp.grid(row=3,column=1)

        Labelws.grid(row=4,column=0)
        Label_ws.config(text=ws,background='#5182cf')
        Label_ws.grid(row=4,column=1)

        Labelstatus.grid(row=5,column=0)
        Label_status.config(text=status,background='#5182cf')
        Label_status.grid(row=5,column=1)

    except Exception as e:
        api = "Error..."

    EmptyLabel = Label(root, text="", background='#5182cf').grid(row=1, column=0)

butn = Button(root, text="Search", command=RealWeather).grid(row=0, column=3)
Label1 = Label(root, text="Enter City: ").grid(row=0,column=0)
city = Entry(root)
city.grid(row=0, column=1, padx=20)

Labelloc = Label(root, text="Location",background='#5182cf')
Label_loc = Label(root)

Labeltemp = Label(root, text="Temperature",background='#5182cf')
Label_temp = Label(root)

Labelws = Label(root, text="Wind Speed",background='#5182cf')
Label_ws = Label(root)

Labelstatus = Label(root, text="Status",background='#5182cf')
Label_status = Label(root)

root.mainloop()

如果你想使用threading ,那么它就像:

# all imports
import threading

.... #same all code 
butn = Button(root, text="Search", command=lambda: threading.Thread(target=RealWeather).start())
btn.grid(row=0, column=3)
.... #same all code

為什么要使用線程? 當 python 從 api 獲取數據時,它不會凍結 GUI。 盡管對tkinter使用線程不是一個很好的選擇,但它也有一些缺點,但對於這個簡單的示例,使用它可能會很好。

以下是如何使用我在評論中提到的通用小部件config()方法來解決您的問題:

from tkinter import *
import requests
import json

root = Tk()
root.title("Weather")
root.geometry("600x400")


def create_labels():
    global Label_loc, Label_temp, Label_ws, Label_status

    Label(root, text="Location",background='#5182cf').grid(row=2,column=0)
    Label_loc = Label(root, background='#5182cf')
    Label_loc.grid(row=2, column=1)

    Label(root, text="Temperature",background='#5182cf').grid(row=3,column=0)
    Label_temp = Label(root, background='#5182cf')
    Label_temp.grid(row=3,column=1)

    Labelws = Label(root, text="Wind Speed", background='#5182cf').grid(row=4,column=0)
    Label_ws = Label(root, background='#5182cf')
    Label_ws.grid(row=4,column=1)

    Labelstatus = Label(root, text="Status", background='#5182cf').grid(row=5,column=0)
    Label_status = Label(root, background='#5182cf')
    Label_status.grid(row=5,column=1)


def RealWeather():
    # Not strickly necessary, but good documentation.
    global Label_loc, Label_temp, Label_ws, Label_status

    try:
        api_request = requests.get("http://api.openweathermap.org/data/2.5/weather?appid=c2fc19de6fcd6869c4a9e167ee0f2eb7&q=" + city.get())
        api = json.loads(api_request.content)
        location = api['name'] + ", " + api['sys']['country']
        temp = int(api['main']['temp'] - 273.15)
        ws = api['wind']['speed']
        status = api['weather'][0]['main']

        Label_loc.config(text=location)
        Label_temp.config(text=temp)
        Label_ws.config(text=ws)
        Label_status.config(text=status)

    except Exception as e:
        print('error occurred:', e)


create_labels()
butn = Button(root, text="Search", command=RealWeather)
butn.grid(row=0, column=3)
Label1 = Label(root, text="Enter City: ")
Label1.grid(row=0,column=0)
city = Entry(root)
city.grid(row=0, column=1, padx=20)

root.mainloop()

PS 我還強烈建議您閱讀並開始遵循PEP 8 - Python 代碼樣式指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM