【问题标题】:Graphs not showing up in tkinter properly图表未正确显示在 tkinter 中
【发布时间】:2017-10-21 04:37:18
【问题描述】:

当我将图表放在我的 tkinter 窗口上时,它会显示所有图表,而不仅仅是一个。我想要的方式是你按下一个按钮,相应的图表就会显示出来(连同其他一些数据)。我相信这是我的按钮的问题,因为它试图一次调用所有股票的功能,而不是根据你按下的按钮一次只调用一个。

import numpy as np
import datetime as dt
import yahoo_finance as yf
import matplotlib.pyplot as plt
from Tkinter import *
import quandl

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


root=Tk()
root.geometry('800x800')
root.title("Stock Information")

f1=Frame(root, width=100, height=100)

f1.pack()


today=dt.date.today()
thirty_days=dt.timedelta(days=43)   

thirty_days_ago=today-thirty_days



def stock_info(stock_name):


    stock=yf.Share(stock_name)
    stock_price=stock.get_price()

    name_price_label=Label(f1, text=(stock_name,':', stock_price),font=("Times New Roman",23))
    name_price_label.grid(row=1, column=3)





    data = quandl.get("WIKI/"+str(stock_name), start_date=str(thirty_days_ago), end_date=str(today),column_index=4)

    fig = plt.figure(1)
    t = np.arange(0.0,3.0,0.01)
    s = np.sin(np.pi*t)
    plt.plot(data)

    canvas = FigureCanvasTkAgg(fig, master=f1)
    plot_widget = canvas.get_tk_widget()
    plot_widget.grid()


apple_button=Button(root,text='AAPL', command=stock_info('AAPL'))

tesla_button=Button(root,text='TSLA', command=stock_info('TSLA'))

google_button=Button(root,text='GOOG', command=stock_info('GOOG'))


apple_button.pack(anchor='w')
tesla_button.pack(anchor='w')
google_button.pack(anchor='w')




root.mainloop()

【问题讨论】:

    标签: python-2.7 matplotlib tkinter


    【解决方案1】:

    将您的按钮创建替换为;

    apple_button=Button(root,text='AAPL', command=lambda:stock_info('AAPL'))
    
    tesla_button=Button(root,text='TSLA', command=lambda:stock_info('TSLA'))
    
    google_button=Button(root,text='GOOG', command=lambda:stock_info('GOOG'))
    

    这样可以确保在单击按钮时调用函数,而不是在创建按钮时调用。

    但是,只要单击按钮,这就会不断添加新图,而不会替换旧图。在添加新图之前,您需要重写代码以删除旧图。我以匿名用户身份超出了每日 Quandl 通话限制,因此无法完成此部分。

    更新

    试试这个:

    import numpy as np
    import datetime as dt
    import yahoo_finance as yf
    import matplotlib.pyplot as plt
    from Tkinter import *
    import quandl
    
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    
    
    root=Tk()
    root.geometry('800x800')
    root.title("Stock Information")
    
    ## Create a main frame
    fmain=Frame(root, width=100, height=100)
    fmain.pack()
    
    #*** Option 2 ***#
    # Not needed if you use Original Option in stock_info function
    ## Create a secondary frame that will be destroy when the next button is clicked
    f1=Frame(fmain, width=100, height=100)
    f1.pack()
    
    today=dt.date.today()
    thirty_days=dt.timedelta(days=43)   
    
    thirty_days_ago=today-thirty_days
    
    
    
    def stock_info(stock_name):
        global f1
    
        #*** Original Option ***#
        ## Destroy the secondary frame if it exists
        # try: 
        #     f1.destroy()
        # except:
        #     pass
    
        #*** Option 2 ***#
        ## Destroy the secondary frame
        f1.destroy()
    
        ## Create a secondary frame that will be destroy when the next button is clicked
        f1=Frame(fmain, width=100, height=100)
        f1.pack()
    
        stock=yf.Share(stock_name)
        stock_price=stock.get_price()
    
        name_price_label=Label(f1, text=(stock_name,':', stock_price),font=("Times New Roman",23))
        name_price_label.grid(row=0, column=2)
    
    
        data = quandl.get("WIKI/"+str(stock_name), start_date=str(thirty_days_ago), end_date=str(today),column_index=4)
    
        fig = plt.figure(figsize=(10,5)) #Change graph size here
        t = np.arange(0.0,3.0,0.01)
        s = np.sin(np.pi*t)
        plt.plot(data)
    
    
        canvas = FigureCanvasTkAgg(fig, master=f1)
        plot_widget = canvas.get_tk_widget()
    
        #Change graph placement here
        #Any widget you grid in row less than 5 will be above this plot
        #Any widget you grid in column less than 2 (0 or 1) will to the left
        #You can chage this row and column number to whatever is appropriate
        plot_widget.grid(row=5, column=2) 
    
    
    apple_button=Button(root,text='AAPL', command=lambda:stock_info('AAPL'))
    tesla_button=Button(root,text='TSLA', command=lambda:stock_info('TSLA'))
    google_button=Button(root,text='GOOG', command=lambda:stock_info('GOOG'))
    
    
    apple_button.pack(anchor='w')
    tesla_button.pack(anchor='w')
    google_button.pack(anchor='w')
    
    root.mainloop()
    

    【讨论】:

    • 哦,好的,非常感谢您的帮助!至于更新图表信息和股票信息,我将如何在不必关闭并重新打开 tkinter 窗口的情况下做到这一点?
    • 我更新了答案,试试看,如果它有效,请告诉我。
    • 谢谢你,效果很好!你能解释一下 global 和 try 部分是如何工作的吗?我不明白那部分是如何工作的。还有没有办法调整图表的大小和位置?我希望它们位于右侧/底部,以便我可以在顶部显示更多信息。再次感谢!!
    • 更新了答案以包括图形大小、名称和价格标签的位置以及一些 cmets。
    • global 关键字在全局命名空间中创建一个变量(使该变量可用于当前函数之外的其他函数/方法)。在这种情况下,它使同一个 f1 可用于函数的多次调用,而不是每个函数调用都创建一个本地 f1。这使得 f1 可以被任何函数调用修改/删除。你可以在this linkor this one了解更多信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 2020-06-01
    • 2017-12-07
    • 1970-01-01
    • 2020-02-15
    相关资源
    最近更新 更多