我正在尝试将 pyplot Figure 对象嵌入到 tkinter GUI 中,然后通过调用
set_size_inches()
方法来更改其大小。
下面提供了一个最小(非)工作示例。有趣的是,图形和画布尺寸的调试打印表明,调整大小确实有效。但是,GUI 中的可见大小保持不变。因此,我认为问题在于调整大小后更新相应的小部件和/或 GUI,但我找不到任何解决方案来将图形的显示更改为其新大小。
import tkinter as tk
from tkinter import Frame
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class Gui(tk.Tk):
def __init__(self):
# initialize tkinter
super().__init__()
# enable fullscreen mode
self.state('zoomed')
# create frame
graph_frame = Frame(self)
# create graph
fig = Figure(figsize=(2, 4), frameon=False, tight_layout=True)
ax = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, master=graph_frame)
# place frame
graph_frame.grid(row=8, column=1, columnspan=8)
graph_frame.columnconfigure(0, weight=1)
graph_frame.columnconfigure(1, weight=1)
graph_frame.columnconfigure(2, weight=1)
graph_frame.rowconfigure(0, weight=1)
graph_frame.rowconfigure(1, weight=1)
graph_frame.rowconfigure(2, weight=2)
# place canvas in grid
canvas_widget = canvas.get_tk_widget()
canvas_widget.grid(row=0, column=0, sticky=tk.NSEW)
canvas_widget.update_idletasks()
# enabling this makes it two graphs:
# canvas_widget.update()
# before info
print('Before resize in inches:')
print(fig.get_size_inches())
print(canvas.get_width_height())
# resize graph
fig.set_size_inches(1, 1)
# after info
print('After resize in inches:')
print(fig.get_size_inches())
print(canvas.get_width_height())
# tried any combination and sequence of these, but none work:
canvas.draw()
canvas.get_tk_widget().update()
canvas.draw_idle()
canvas.flush_events()
graph_frame.update()
self.update()
if __name__ == '__main__':
# run GUI
gui = Gui()
gui.mainloop()
结果:
无需额外的
canvas_widget.update()
调用:
额外的
canvas_widget.update()
电话:
我尝试更新和刷新现有的每个可能的小部件和根,但没有任何效果。
很高兴收到有关我做错了什么或我如何滥用东西的任何提示:-)
您可以根据所需的图大小更改画布尺寸:
fig.set_size_inches(1, 1, forward = True)
canvas.get_tk_widget().configure(width=fig.get_figwidth()*100, height=fig.get_figheight()*100)