【问题标题】:display and save a piechart with tkinter使用 tkinter 显示和保存饼图
【发布时间】:2020-09-10 13:33:48
【问题描述】:

1) 我的列表框有问题,当用户在列表框中选择一个国家/地区名称时,我希望它显示名称作为条目(默认文本)。

2) 之后,当我点击保存按钮时,它显示错误(实际上,我不知道是怎么回事)。用户可以输入所需国家的名称(一切皆有可能)。

3) 我有一个问题没有得到它。(我在下面评论了它)

编辑: 1)发现问题后,我需要优化我的程序。我不知道为什么要花这么多时间从网站获取数据?

2) 点击“显示数据”按钮时,我需要一个标签来显示输出

谢谢。

    from covid import *
    from tkinter import *
    import tkinter as tk   
    import matplotlib.pyplot as plt
    import pandas as pd
    import pickle
    import seaborn as sb  

def main():
    win=Tk()
    win.geometry("400x400")
    lbl=Label(win,text="Write ur country name:")
    lbl.pack()

    #print(country_name)

    covid=Covid()
    #covid_general=Covid(source="worldometers")

    in_country=Entry(win)
    in_country.pack()
    country_name=in_country.get()

    def list_country():
        lst_country=covid.list_countries()
        lbl_countries=Listbox(win,font=("times",14))
        lbl_countries.pack(expand=1,fill=BOTH)


        for names in lst_country:


            lbl_countries.insert(END,names)

        '''
        for item in name:
            in_country.insert(END,lbl_countries.get(item))
            print(item)
        '''

    def save_data():

        country=covid.get_status_by_country_name(country_name)


    #what does this do?key:country[key]
        data={
            key:country[key]
            for key in country.keys() and {'confirmed','active','deaths','recovered'}

        }
        #save the data to a file covid.pkl
        a_file=open("covid.pkl","wb")
        pickle.dump(data,a_file)
        a_file.close()
    def load_data():

        #read the data from covid.pkl
        a_file=open("covid.pkl","rb")
        output_a=pickle.load(a_file)

        #now get data to data frame
        df_a=pd.DataFrame(output_a,index=[country_name],columns=['active','deaths','recovered'])

        #filter data again with the numbers only.using dataframe
        df_b=df_a.loc[country_name]
        #check output
        print(df_a)

        #reforming pieplot
        labels = ['active','deaths','recovered']
        colors=['orange','red','green']
        explode=(0,0.2,0)

        #now plot the data 
        plt.title("Covid Chart")
        main_data=plt.pie(df_a,explode=explode,labels=df_b,colors=colors,autopct='%1.1f%%',startangle=140)
        plt.legend(labels,loc="upper left")
        plt.show()






    btn_save=Button(win,text="Save",command=save_data)
    btn_load=Button(win,text="load_data",command=load_data)
    btn_list=Button(win,text="Show Countries Name",command=list_country)

    btn_save.pack()
    btn_load.pack()
    btn_list.pack()    

    win.mainloop()
if __name__=="__main__":
    main()

【问题讨论】:

    标签: python pandas matplotlib tkinter pickle


    【解决方案1】:

    所以,我发现了我所有的问题......

    这是我的最终代码:

    from covid import *
    from tkinter import *
    from tkinter import messagebox
    import tkinter as tk
    import matplotlib.pyplot as plt
    import pandas as pd
    import pickle
    import seaborn as sb
    
    country_get = None
    
    
    def main():
        global country_get
        win = Tk()
        win.geometry("300x400")
        win.title("")
        win.configure(bg="#fffaf0")
        win.resizable(False, False)
        #win.iconbitmap(r'D:/Python.p/Mine/Simple Projects/covid/py.ico')
    
        lbl_intro = Label(win, text="Covid-19 per country", font=("Arial", 16))
        lbl_intro.pack()
    
        covid = Covid()
        covid_general = Covid(source="worldometers")
    
        # def list_country():
        F1 = Frame(borderwidth=2, relief='ridge')
        F1.pack()
        lst_country = covid_general.list_countries()
        lst_country = sorted(lst_country)
        lb_countries = Listbox(F1, font=("times", 14), bg='#f5f5f5')
    
        s = Scrollbar(F1)
        lb_countries.pack(side=LEFT, expand=1, fill=X)
        s.pack(side=RIGHT, fill=Y)
    
        s['command'] = lb_countries.yview
        lb_countries['yscrollcommand'] = s.set
        #lb_countries.insert(END,"Country List:")
        for names in lst_country:
            lb_countries.insert(END, names)
    
        def get_country(*args):
            # gets which country is selected, and changes the label accordingly
    
            global country_get
            country_get = lst_country[lb_countries.curselection()[0]]
    
        lb_countries.bind("<<ListboxSelect>>", get_country)
    
        def save_data():
    
            country = covid.get_status_by_country_name(country_get)
    
            # filtering the data.using the online database
            data = {
                key: country[key]
                for key in country.keys() and {'confirmed', 'active', 'deaths', 'recovered'}
    
            }
            print(data)
            # print(country_general)
            messagebox.showinfo("Covid Data", data)
            # save the data to a file covid.pkl
            a_file = open("covid.pkl", "wb")
            pickle.dump(data, a_file)
            a_file.close()
    
        def load_data():
    
            # read the data from covid.pkl
            a_file = open("covid.pkl", "rb")
            output_a = pickle.load(a_file)
    
            # now get data to data frame
            df_a = pd.DataFrame(output_a, index=[country_get], columns=[
                                'active', 'deaths', 'recovered'])
    
            # filter data again with the numbers only.using dataframe
            df_b = df_a.loc[country_get]
    
            # reforming pieplot
            labels = ['active', 'deaths', 'recovered']
            colors = ['orange', 'red', 'green']
            explode = (0, 0.2, 0)
    
            # now plot the data
            plt.title("Covid Chart")
            main_data = plt.pie(df_a, explode=explode, labels=df_b,
                                colors=colors, autopct='%1.1f%%', startangle=90)
            plt.legend(labels, loc="best")
    
            # fig.canvas.set_window_title('Window')
            plt.show()
        btn_save = Button(win, text="Show Data", padx=10, pady=4, fg='blue', font=(
            'arial', 12, 'bold'), bg='#e2e21d', command=save_data)
        btn_load = Button(win, text="Show Plot", padx=10, pady=4, font=(
            'arial', 12, 'bold'), bg='#e2e21d', fg='blue', command=load_data)
        btn_quit = Button(win, fg='white', padx=12, pady=8, font=('arial', 12, 'bold'), text="Exit",
                        command=lambda: win.quit(), bg='#0073cf')
        
        btn_quit.pack(side=BOTTOM)
        btn_save.pack(side=RIGHT)
        btn_load.pack(side=LEFT)
    
        win.mainloop()
    
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

      【解决方案2】:

      要实现您想要的,您需要使用Treeview 小部件。

      此外,要使树视图可编辑(如您所说,使用文本框),请参阅answer

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 2020-04-13
        • 2019-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多