我已将一个matplotlib图表添加到我的tkinter窗口中,但每次我点击“确定”并将其添加到应用程序中时,它会重新调整整个窗口大小,并且还会切断轴刻度。我尝试过调整
我简化了代码,使其可以通过单击“确定”来运行。
点击“确定”之前:
点击“确定”之后:
![After](https://istack.dev59.com/ksb7B.webp)
figsize
和canvas
,但无法解决这个问题。有人能解释一下这种行为的原因吗?我简化了代码,使其可以通过单击“确定”来运行。
点击“确定”之前:
![Before](https://istack.dev59.com/nEgFZ.webp)
![After](https://istack.dev59.com/ksb7B.webp)
from tkinter import *
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class StockApp(Frame):
def __init__(self, master):
super(StockApp, self).__init__(master)
self.place()
self.widgets()
def widgets(self):
# width * height
root.geometry('500x400')
root.configure(bg='#FFFFFF')
# Header
header_label = Label(text='Stock Prices', font=(
'Calibri', 22, 'bold'), bg='#FFFFFF')
header_label.place(x=30, y=15)
# Enter your API key
api_key_label = Label(text='API key', font=(
'Calibri', 10), bg='#FFFFFF')
api_key_label.place(x=30, y=65)
self.api_key_field = Entry(
width=32, font=('Calibri', 10), bg='#F4F4F4')
self.api_key_field.config(show="*")
self.api_key_field.place(x=30, y=90)
# Enter an index
index_label = Label(text='Stock index', font=(
'Calibri', 10), bg='#FFFFFF')
index_label.place(x=280, y=65)
self.index_field = Entry(width=15, font=('Calibri', 10), bg='#F4F4F4')
self.index_field.place(x=280, y=90)
# OK button
ok_btn = Button(text='OK', command=self.ok, font=(
'Calibri', 8), bg='#F4F4F4', width=5)
ok_btn.place(x=400, y=88)
def call_api(self):
pass
def format_df(self):
self.df = pd.DataFrame({'date': ['2020-11-06', '2020-11-07', '2020-11-08', '2020-11-09'], 'adj_close': [200, 210, 205, 215]})
self.df['date'] = pd.to_datetime(self.df['date'])
self.df.set_index('date', inplace = True)
def draw_chart(self):
#plot data
fig, ax = plt.subplots(figsize=(2,1), dpi=50)
self.df.plot(ax=ax)
# #set major ticks format
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_legend().remove()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw() # TK-Drawingarea
# Do I need to place both?
canvas.get_tk_widget().place(x = 30, y = 150)
canvas._tkcanvas.place(x = 30, y = 150)
def ok(self):
self.call_api()
self.format_df()
self.draw_chart()
if __name__ == "__main__":
root= Tk()
app= StockApp(root)
root.title('Stock prices')
mainloop()
figsize=(2,1)
太小了,请尝试更大的值。并且您使用place()
来布置小部件,它不会缩小窗口。 - acw1668