嵌入tkinter窗口中的Matplotlib图形在顶部有一个奇怪的灰色“条”
问题描述:
我创建了一个matplotlib条形图来显示当前降水,高温和低温月份的平均值。我已经存储,因为你要导入到它transclude成Tkinter的窗口,像这样的模块的量在像这样一个单独的模块matplotlib代码:嵌入tkinter窗口中的Matplotlib图形在顶部有一个奇怪的灰色“条”
from functions import Statistics
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *
class Plot:
def __init__(self, key, zipcode, tk):
self.tk = tk
self.tk.wm_title('Weather')
stats = Statistics(zipcode, key)
self.f = Figure(figsize=(6, 6))
self.a = self.f.add_subplot(111)
self.t = ('Precip (In.)', 'High (F)', 'Low (F)')
self.tt = np.arange(len(self.t))
self.s = [float(stats.avg_precip), float(stats.avg_high), float(stats.avg_low)]
self.a.bar(self.tt, self.s, color = 'red', align='center')
self.a.set_title(stats.title)
self.a.set_xticklabels(self.t)
self.a.set_xticks(self.tt)
self.canvas = FigureCanvasTkAgg(self.f, master=self.tk)
def show(self):
self.canvas.show()
self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=1)
self.canvas._tkcanvas.pack(side=BOTTOM, fill=BOTH, expand=1)
我已经测试类和函数一个单独的脚本在这里:
from plot import Plot
from data import Data
data = Data()
from tkinter import *
tk = Tk()
plt = Plot(data.api_key3, '57064', tk)
plt.show()
It works exactly as I want it to.
但是!
当我尝试将它实现到主脚本中时;
def stats(key, zipcode):
unpack()
plot = Plot(key, zipcode, tk)
plot.show()
按此按钮执行;
btn_3 = Button(tk, text="Statistics", command = lambda: stats(data.api_key3, ent.get()))
它不显示图形,but there is now a very ugly gray "bar" at the top
以下是完整的主脚本:
import logging
LOG_FILENAME='error_log.log'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
logging.debug('WeatherLog')
from tkinter import *
tk = Tk()
tk.resizable(0,0)
import tkinter.messagebox
from img import *
img = Images()
from data import Data
data = Data()
from functions import Current_weather, Alerts, Forecast
from plot import Plot
canvas = Canvas(tk, width=275, height=100)
tk.wm_iconbitmap("cloud.ico")
tk.title("Weather")
canvas.pack()
lbl = Label(tk, text="Enter Zip Code")
ent = Entry(tk)
def pack():
lbl.place(x=100, y=12)
ent.place(x=80, y=40)
btn.place(anchor=CENTER, height=25, width = 65, x = 140, y = 85)
btn_2.place(anchor=CENTER, height=25, width = 65, x = 45, y = 85)
btn_3.place(anchor=CENTER, height=25, width=65, x=235, y=85)
def unpack():
lbl.place_forget()
ent.place_forget()
btn.place_forget()
btn_2.place_forget()
btn_3.place_forget()
def about():
logo = Logo()
toplevel = Toplevel(width=300, height=165)
toplevel.resizable(0,0)
toplevel.wm_iconbitmap("cloud.ico")
toplevel.title("About this program...")
about_text = Label(toplevel, text="Created by Michelle")
about_text2 = Label(toplevel, text="Special thanks to all the folks on the freenode network")
about_text3 = Label(toplevel, text="API provided by:")
blankspace = Label(toplevel, text=" ")
logo_image = Label(toplevel, image = logo.logo)
logo_image.image = logo.logo
about_text.pack()
about_text2.pack()
about_text3.pack()
blankspace.pack()
logo_image.pack()
def stats(key, zipcode):
unpack()
plot = Plot(key, zipcode, tk)
plot.show()
def return_2_form2():
for x in range(4):
canvas.delete("img%s" % x)
for x in range(12):
canvas.delete("line%s" % x)
for x in range(3):
canvas.delete("br%s" % x)
canvas.delete("title")
canvas.config(width=275, height=100, background=data.default_color)
goback_button2.pack_forget()
pack()
def forecast(key, zipcode):
try:
forecast = Forecast(key, zipcode)
current_weather = Current_weather(key, zipcode)
unpack()
if data.hour >= 15 or data.hour <= 6:
bg = data.night_color
weather_icon = img.weather_icon_night
text_color = data.night_text_color
elif data.hour <= 16 or data.hour >= 7:
bg = data.day_color
weather_icon = img.weather_icon_day
text_color = data.day_text_color
canvas.config(width=350, height=475, background=bg)
canvas.create_text(175, 15, text= "Forecast for %s, %s" % (current_weather.city, current_weather.state), font=('Fixedsys', 12), fill=text_color , tag="title")
for x in range(4):
canvas.create_image(25, 75+100*x, anchor=NW, image=weather_icon[forecast.days[x].conditions], tag="img%s" % x)
canvas.create_text(50, 65+100*x, text="%s" % forecast.days[x].weekday, font=('Fixedsys', 6), fill=text_color, tag="line%s" % x)
canvas.create_text(225, 70+100*x, text="%s" % forecast.days[x].conditions, font=('Fixedsys', 6), fill=text_color, tag="line%s" % str(x+1))
canvas.create_text(225, 90+100*x, text="High: %s , Low: %s" % (forecast.days[x].high, forecast.days[x].low), font=('Fixedsys', 6), fill=text_color, tag="line%s" % str(x+2))
canvas.create_text(225, 110+100*x, text="Wind: %s %s" % (forecast.days[x].wind_speed, forecast.days[x].wind_direction), font=('Fixedsys', 6), fill=text_color, tag="line%s" % str(x+3))
for x in range(3):
canvas.create_line(35, 140+100*x, 315, 140+100*x, fill=text_color, tag="br%s" % x)
goback_button2.pack()
except:
tkinter.messagebox.showerror("Something went wrong.", "Unable to fetch forecast. Either you entered an invalid zip code, or you've hit the maximum daily requests.")
logging.exception('Unhandled exception:')
raise
def return_2_form():
canvas.config(width=275, height=100, background=data.default_color)
canvas.delete("banner")
canvas.delete("alert")
canvas.delete("img")
for x in range(1, 6):
canvas.delete("line%s" % x)
goback_button.pack_forget()
pack()
def current_weather(key, zipcode):
try:
current_weather = Current_weather(key, zipcode)
alerts = Alerts(key, zipcode)
unpack()
bg = None
weather_icon = None
text_color = None
if data.hour >= 15 or data.hour <= 6:
bg = data.night_color
weather_icon = img.weather_icon_night
text_color = data.night_text_color
elif data.hour <= 16 or data.hour >= 7:
bg = data.day_color
weather_icon = img.weather_icon_day
text_color = data.day_text_color
if alerts.check_alerts():
canvas.create_rectangle(0, 0, 552, 30, fill = '#FF5D00', tag="banner")
canvas.create_text(275, 15, text= "%s Effective until %s" % (alerts.description, alerts.expires), font=('Fixedsys', 10), tag="alert")
canvas.config(width=550, height=225, background=bg)
else:
canvas.create_rectangle(0, 0, 552, 30, fill = '#FF5D00', tag="banner")
canvas.create_text(275, 15, text= "No Alerts Active", font=('Fixedsys', 10), tag="alert")
canvas.config(width=550, height=225, background=bg)
canvas.create_image(25, 70, anchor=NW, image=weather_icon[current_weather.weather], tag="img")
canvas.create_text(275, 80, text= "%s, %s" % (current_weather.city, current_weather.state), font=('Fixedsys', 18), fill=text_color, tag="line1")
canvas.create_text(275, 145, text= "The weather is currently %s" % current_weather.weather, font=('Fixedsys', 16), fill=text_color, tag="line2")
canvas.create_text(275, 160, text= "The temperature is %s" % current_weather.temperature_string, font=('Fixedsys', 16), fill=text_color, tag="line3")
canvas.create_text(275, 175, text= "But, it feels like %s" % current_weather.feelslike_string, font=('Fixedsys', 16), fill=text_color, tag="line4")
canvas.create_text(275, 190, text= "Wind is blowing %s" % current_weather.wind_string, font=('Fixedsys', 16), fill=text_color, tag="line5")
goback_button.pack()
except:
tkinter.messagebox.showerror("Something went wrong.", "Unable to fetch weather conditions. Either you entered an invalid zip code, or you've hit the maximum daily requests.")
logging.exception('Unhandled exception:')
raise
menubar = Menu(tk)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help")
helpmenu.add_separator()
helpmenu.add_command(label="About", command=about)
menubar.add_cascade(label="Help", menu=helpmenu)
tk.config(menu=menubar)
btn = Button(tk, text="Current", command = lambda: current_weather(data.api_key3, ent.get()))
btn_2 = Button(tk, text="Forecast", command = lambda: forecast(data.api_key3, ent.get()))
btn_3 = Button(tk, text="Statistics", command = lambda: stats(data.api_key3, ent.get()))
goback_button = Button(tk, text="Go back", command=return_2_form)
goback_button2 = Button(tk, text="Go back", command=return_2_form2)
goback_button3 = Button(tk, text='Go back',)
pack()
canvas.mainloop()
答
的灰色条是由帆布占用的面积,你解压的lbl
,ent
, btn
,btn_2
和btn_3
,但没有解压canvas
。将canvas.pack_forget()
添加到unpack
函数。
另外,不建议在同一主/父母使用多个形状管理(你的画布,place
在其他窗口小部件共享tk
父所使用pack
。