Python Tkinter中嵌入的Matplotlib图形仅在';g';在按键事件时按下。为什么?
我试图找到一种方法,通过更新数据来更新嵌入在tkinter窗口类中的matplotlib图像打印。通过单击按钮修改数据,并使用numpy数组存储/操作数据 我没有成功地删除类实例,但我已经能够嵌入静态图 我试着忘记你的包,但没有成功Python Tkinter中嵌入的Matplotlib图形仅在';g';在按键事件时按下。为什么?,python,numpy,user-interface,matplotlib,tkinter,Python,Numpy,User Interface,Matplotlib,Tkinter,我试图找到一种方法,通过更新数据来更新嵌入在tkinter窗口类中的matplotlib图像打印。通过单击按钮修改数据,并使用numpy数组存储/操作数据 我没有成功地删除类实例,但我已经能够嵌入静态图 我试着忘记你的包,但没有成功 import tkinter from random import randint import matplotlib as plt import numpy as np from matplotlib.backends.backend_tkagg import
import tkinter
from random import randint
import matplotlib as plt
import numpy as np
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
#create figure
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_axes([0,0,1,1])
ax.imshow(np.array([[0,10],[23,40]]))
#plt.rcParams["keymap.grid"] = ""
#create canvas with figure
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def on_key_press(event):
#if event.key == 'x':
ax.imshow(np.array([[randint(0,30),randint(0,30)],[randint(0,30),randint(0,30)]]))
key_press_handler(event, canvas) # toolbar)
print("you pressed {}".format(event.key))
#connect canvas to event function
canvas.mpl_connect("key_press_event", on_key_press)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
窗口中会出现多个图形,而不是更新到同一个图形要清除当前绘图,请调用
ax.clear()
。然后可以使用ax.imshow(…)
,最后使用canvas.draw\u idle
重新绘制画布,如下所示:
def on_key_press(event):
ax.clear()
ax.imshow(np.array([[randint(0,30),randint(0,30)],[randint(0,30),randint(0,30)]]))
canvas.draw_idle()
key_press_handler(event, canvas)
print("you pressed {}".format(event.key))