为什么 Tkinter 窗口打开这么慢?

时间:2021-03-22 16:45:49

标签: python tkinter api-design

我编写了一个转换加密货币的程序,带有一个基本的用户界面(稍后会使用)。我的代码有效,但由于某种原因,tkinter 窗口打开速度很慢。是否与我的代码中有太多 API 请求有关,还是其他原因?如何让程序运行得更快?

代码如下:

def GUIinterfaceConversion():
    # Retrieve the api data
    apiURL = "https://api.nomics.com/v1/currencies/ticker?key=my_key"
    rawData = requests.get(apiURL)
    data = json.loads(rawData.text)

    # Get the Currency Abbreviations & Full Names
    currencyOutputs = []
    for element in data:
        currencyOutput = {"Name":element["name"],"Abbreviation":element["currency"]}
        currencyOutputs.append(currencyOutput)

    # Window Layout
    window = tk.Tk()
    window.title("Cryptocurrency Converter")
    window.geometry("1300x1000")

    # Listbox Layout
    Lb1 = tk.Listbox(window, width=40, height=20)
    Lb2 = tk.Listbox(window, width=40, height=20)
    for output in currencyOutputs:
        Lb1.insert(0, output["Name"] + "(" + output["Abbreviation"] + ")")
        Lb2.insert(0, output["Name"] + "(" + output["Abbreviation"] + ")")

    Lb1.place(relx=0.3, rely=0.3, anchor="center")
    Lb2.place(relx=0.7, rely=0.3, anchor="center")

    # On Selection
    Label1 = tk.Label(window, text="")
    Label1.place(relx=0.3,rely=0.55,anchor="center")
    Label2 = tk.Label(window, text="")
    Label2.place(relx=0.7,rely=0.55,anchor="center")
    def labelChange(event, label, listbox):
        label['text'] = "Converting From: " + listbox.get(listbox.curselection())
    
    Lb1.bind('<<ListboxSelect>>', lambda _: labelChange(event=any,label=Label1,listbox=Lb1))
    Lb2.bind('<<ListboxSelect>>', lambda _: labelChange(event=any,label=Label2,listbox=Lb2))

    # Conversion Label
    LabelConverted = tk.Label(window)
    LabelConverted.place(relx=0.5,rely=0.65,anchor="center")

    # Conversion Button
    def convert():
        firstElement = Label1['text'].split(': ')[1].split("(")[1].split(")")[0]
        secondElement = Label2['text'].split(': ')[1].split("(")[1].split(")")[0]

        # Get API
        convertingApi = f"https://api.nomics.com/v1/currencies/ticker?key=my_key={firstElement}"
        convertedApi = f"https://api.nomics.com/v1/currencies/ticker?key=my_key&ids={secondElement}"
        converting = json.loads(requests.get(convertingApi).text)
        converted = json.loads(requests.get(convertedApi).text)

        # Generate the ratio and the final amount
        twoCurrenciesRatio = float(converting[0]['price'])/float(converted[0]['price'])
        finalAmount = format(twoCurrenciesRatio,'.8f')
        LabelConverted['text'] = finalAmount

    B = tk.Button(window, text="Convert", command=convert)
    B.place(relx=0.5,rely=0.55,anchor="center")

    window.mainloop()

GUIinterfaceConversion()

非常感谢 :)

1 个答案:

答案 0 :(得分:0)

没关系,由于某种原因,它今天的运行速度更快了。如果我有任何其他问题需要处理,我会告诉您。

相关问题