我有一个Tkinter GUI,它显示一个Matplotlib图(带有Matplotlib 1.2.0rc2的Python 2.7.3),并允许用户配置图的某些方面。情节往往会变大,所以这个数字被包裹在一个滚动的画布中。配置图的一个方面是改变其大小。
虽然一方面情节滚动正确,另一方面调整大小也适用,但这两个操作不能组合使用。下面是一个演示效果的脚本。 (对不起长度,我无法更短。)你可以滚动绘图(使用滚动条),它可以做得越来越小(使用按钮)。但是,每当滚动时,图形将重置为原始大小。显然,我希望通过使用滚动条不会改变图形的大小。
import math
from Tkinter import Tk, Button, Frame, Canvas, Scrollbar
import Tkconstants
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def addScrollingFigure(figure, frame):
# set up a canvas with scrollbars
canvas = Canvas(frame)
canvas.grid(row=0, column=0, sticky=Tkconstants.NSEW)
xScrollbar = Scrollbar(frame, orient=Tkconstants.HORIZONTAL)
yScrollbar = Scrollbar(frame)
xScrollbar.grid(row=1, column=0, sticky=Tkconstants.EW)
yScrollbar.grid(row=0, column=1, sticky=Tkconstants.NS)
canvas.config(xscrollcommand=xScrollbar.set)
xScrollbar.config(command=canvas.xview)
canvas.config(yscrollcommand=yScrollbar.set)
yScrollbar.config(command=canvas.yview)
# plug in the figure
figAgg = FigureCanvasTkAgg(figure, canvas)
mplCanvas = figAgg.get_tk_widget()
mplCanvas.grid(sticky=Tkconstants.NSEW)
# and connect figure with scrolling region
canvas.create_window(0, 0, window=mplCanvas)
canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL))
def changeSize(figure, factor):
oldSize = figure.get_size_inches()
print "old size is", oldSize
figure.set_size_inches([factor * s for s in oldSize])
print "new size is", figure.get_size_inches()
print
figure.canvas.draw()
if __name__ == "__main__":
root = Tk()
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
frame = Frame(root)
frame.grid(column=0, row=0, sticky=Tkconstants.NSEW)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
figure = plt.figure(dpi=150, figsize=(4, 4))
plt.plot(xrange(10), [math.sin(x) for x in xrange(10)])
addScrollingFigure(figure, frame)
buttonFrame = Frame(root)
buttonFrame.grid(row=0, column=1, sticky=Tkconstants.NS)
biggerButton = Button(buttonFrame, text="larger",
command=lambda : changeSize(figure, 1.5))
biggerButton.grid(column=0, row=0)
smallerButton = Button(buttonFrame, text="smaller",
command=lambda : changeSize(figure, .5))
smallerButton.grid(column=0, row=1)
root.mainloop()
我想我错过了一些情节和情节。滚动画布连在一起;我尝试在每次canvas.create_window(...)
调用后重新配置滚动画布(使用canvas.config(...)
和changeSize
),但这没有帮助。我开始工作的另一个选择是在每次调整大小后重新生成整个设置(图形,画布,滚动条)。 (然而,除了看似有点残酷之外,还有一个问题就是我无法正确处理旧数据,使程序随着时间的推移积累了相当多的内存。)
那么,有没有人对如何在调整大小操作后使这些滚动条正常运行有任何想法?
答案 0 :(得分:3)
右;在this answer中的滚动条讨论之后,我最终完成了这个:
..而且我认为我设法得到了一种缩放代码,它也可以缩放(有些)标签和填充,因此(大约)整个绘图适合内部(注意,第二个图像使用“中等”缩放来自imgur) :
对于非常小的尺寸,标签会再次开始消失 - 但它仍适用于各种尺寸。
请注意,对于较新的matplotlib
(> = 1.1.1),有一个函数figure.tight_layout()
可以为这样的情况设置边距(但不是字体大小)(它是一个subplot) - 但如果您使用较旧的matplotlib
,则可以figure.subplots_adjust(left=0.2, bottom=0.15, top=0.86)
执行此示例所做的操作;并已经过测试:
$ python2.7 -c 'import matplotlib; print(matplotlib.__version__)'
0.99.3
$ python3.2 -c 'import matplotlib; print(matplotlib.__version__)'
1.2.0
(我确实试着看看我是否可以为较旧的matplotlib复制tight_layout
- 遗憾的是,它需要tight_layout.py中包含的一组相当复杂的函数,而这些函数又需要图和轴也有特定的规格,v.0.99中没有)
由于subplots_adjust
采用相对参数(从0.0到1.0),我们原则上只需设置一次 - 并希望它们适用于我们所需的比例范围。其余的(缩放字体和标签)请参阅下面的代码:
import math
import sys
if sys.version_info[0] < 3:
from Tkinter import Tk, Button, Frame, Canvas, Scrollbar
import Tkconstants
else:
from tkinter import Tk, Button, Frame, Canvas, Scrollbar
import tkinter.constants as Tkconstants
import matplotlib
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pprint, inspect
frame = None
canvas = None
ax = None
def printBboxes(label=""):
global canvas, mplCanvas, interior, interior_id, cwid, figure
print(" "+label,
"canvas.bbox:", canvas.bbox(Tkconstants.ALL),
"mplCanvas.bbox:", mplCanvas.bbox(Tkconstants.ALL),
"subplotpars:", figure.subplotpars.__dict__ )
def addScrollingFigure(figure, frame):
global canvas, mplCanvas, interior, interior_id, cwid
# set up a canvas with scrollbars
canvas = Canvas(frame)
canvas.grid(row=1, column=1, sticky=Tkconstants.NSEW)
xScrollbar = Scrollbar(frame, orient=Tkconstants.HORIZONTAL)
yScrollbar = Scrollbar(frame)
xScrollbar.grid(row=2, column=1, sticky=Tkconstants.EW)
yScrollbar.grid(row=1, column=2, sticky=Tkconstants.NS)
canvas.config(xscrollcommand=xScrollbar.set)
xScrollbar.config(command=canvas.xview)
canvas.config(yscrollcommand=yScrollbar.set)
yScrollbar.config(command=canvas.yview)
# plug in the figure
figAgg = FigureCanvasTkAgg(figure, canvas)
mplCanvas = figAgg.get_tk_widget()
# and connect figure with scrolling region
cwid = canvas.create_window(0, 0, window=mplCanvas, anchor=Tkconstants.NW)
printBboxes("Init")
changeSize(figure, 1)
def changeSize(figure, factor):
global canvas, mplCanvas, interior, interior_id, frame, cwid
oldSize = figure.get_size_inches()
print("old size is", oldSize)
figure.set_size_inches([factor * s for s in oldSize])
wi,hi = [i*figure.dpi for i in figure.get_size_inches()]
print("new size is", figure.get_size_inches())
print("new size pixels: ", wi,hi)
mplCanvas.config(width=wi, height=hi) ; printBboxes("A")
canvas.itemconfigure(cwid, width=wi, height=hi) ; printBboxes("B")
canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)
tz.set_fontsize(tz.get_fontsize()*factor)
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(item.get_fontsize()*factor)
ax.xaxis.labelpad = ax.xaxis.labelpad*factor
ax.yaxis.labelpad = ax.yaxis.labelpad*factor
#figure.tight_layout() # matplotlib > 1.1.1
figure.subplots_adjust(left=0.2, bottom=0.15, top=0.86)
figure.canvas.draw() ; printBboxes("C")
print()
if __name__ == "__main__":
global root, figure
root = Tk()
root.rowconfigure(1, weight=1)
root.columnconfigure(1, weight=1)
frame = Frame(root)
frame.grid(column=1, row=1, sticky=Tkconstants.NSEW)
frame.rowconfigure(1, weight=1)
frame.columnconfigure(1, weight=1)
figure = plt.figure(dpi=150, figsize=(4, 4))
ax = figure.add_subplot(111)
ax.plot(range(10), [math.sin(x) for x in range(10)])
#tz = figure.text(0.5,0.975,'The master title',horizontalalignment='center', verticalalignment='top')
tz = figure.suptitle('The master title')
ax.set_title('Tk embedding')
ax.set_xlabel('X axis label')
ax.set_ylabel('Y label')
print(tz.get_fontsize()) # 12.0
print(ax.title.get_fontsize(), ax.xaxis.label.get_fontsize(), ax.yaxis.label.get_fontsize()) # 14.4 12.0 12.0
addScrollingFigure(figure, frame)
buttonFrame = Frame(root)
buttonFrame.grid(row=1, column=2, sticky=Tkconstants.NS)
biggerButton = Button(buttonFrame, text="larger",
command=lambda : changeSize(figure, 1.2))
biggerButton.grid(column=1, row=1)
smallerButton = Button(buttonFrame, text="smaller",
command=lambda : changeSize(figure, 0.833))
smallerButton.grid(column=1, row=2)
qButton = Button(buttonFrame, text="quit",
command=lambda : sys.exit(0))
qButton.grid(column=1, row=3)
root.mainloop()
答案 1 :(得分:2)
我刚刚碰到同样的问题 - 据我所知(通过实验),除了figure.set_size_inches()
之外,还必须设置mplCanvas
的新大小和画布创建的窗口的新大小对于它,在做figure.canvas.draw()
之前(然后也迫使一个人使用全局变量 - 或类定义)。此外,显然不需要“网格”mplCanvas
- 因为它已经是canvas
的孩子,已经是“网格”ded。并且可能想要锚定NW,因此在每次调整大小时,绘图将重新绘制在左上角的0,0处。
这对我有用(我也尝试使用Python Tkinter scrollbar for frame中的“内部”框架,但这不起作用;其中一些留在代码段的末尾):
import math
import sys
if sys.version_info[0] < 3:
from Tkinter import Tk, Button, Frame, Canvas, Scrollbar
import Tkconstants
else:
from tkinter import Tk, Button, Frame, Canvas, Scrollbar
import tkinter.constants as Tkconstants
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pprint
frame = None
canvas = None
def printBboxes(label=""):
global canvas, mplCanvas, interior, interior_id, cwid
print(" "+label,
"canvas.bbox:", canvas.bbox(Tkconstants.ALL),
"mplCanvas.bbox:", mplCanvas.bbox(Tkconstants.ALL))
def addScrollingFigure(figure, frame):
global canvas, mplCanvas, interior, interior_id, cwid
# set up a canvas with scrollbars
canvas = Canvas(frame)
canvas.grid(row=1, column=1, sticky=Tkconstants.NSEW)
xScrollbar = Scrollbar(frame, orient=Tkconstants.HORIZONTAL)
yScrollbar = Scrollbar(frame)
xScrollbar.grid(row=2, column=1, sticky=Tkconstants.EW)
yScrollbar.grid(row=1, column=2, sticky=Tkconstants.NS)
canvas.config(xscrollcommand=xScrollbar.set)
xScrollbar.config(command=canvas.xview)
canvas.config(yscrollcommand=yScrollbar.set)
yScrollbar.config(command=canvas.yview)
# plug in the figure
figAgg = FigureCanvasTkAgg(figure, canvas)
mplCanvas = figAgg.get_tk_widget()
#mplCanvas.grid(sticky=Tkconstants.NSEW)
# and connect figure with scrolling region
cwid = canvas.create_window(0, 0, window=mplCanvas, anchor=Tkconstants.NW)
printBboxes("Init")
canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)
def changeSize(figure, factor):
global canvas, mplCanvas, interior, interior_id, frame, cwid
oldSize = figure.get_size_inches()
print("old size is", oldSize)
figure.set_size_inches([factor * s for s in oldSize])
wi,hi = [i*figure.dpi for i in figure.get_size_inches()]
print("new size is", figure.get_size_inches())
print("new size pixels: ", wi,hi)
mplCanvas.config(width=wi, height=hi) ; printBboxes("A")
#mplCanvas.grid(sticky=Tkconstants.NSEW)
canvas.itemconfigure(cwid, width=wi, height=hi) ; printBboxes("B")
canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)
figure.canvas.draw() ; printBboxes("C")
print()
if __name__ == "__main__":
root = Tk()
root.rowconfigure(1, weight=1)
root.columnconfigure(1, weight=1)
frame = Frame(root)
frame.grid(column=1, row=1, sticky=Tkconstants.NSEW)
frame.rowconfigure(1, weight=1)
frame.columnconfigure(1, weight=1)
figure = plt.figure(dpi=150, figsize=(4, 4))
plt.plot(range(10), [math.sin(x) for x in range(10)])
addScrollingFigure(figure, frame)
buttonFrame = Frame(root)
buttonFrame.grid(row=1, column=2, sticky=Tkconstants.NS)
biggerButton = Button(buttonFrame, text="larger",
command=lambda : changeSize(figure, 1.5))
biggerButton.grid(column=1, row=1)
smallerButton = Button(buttonFrame, text="smaller",
command=lambda : changeSize(figure, .5))
smallerButton.grid(column=1, row=2)
root.mainloop()
"""
interior = Frame(canvas) #Frame(mplCanvas) #cannot
interior_id = canvas.create_window(0, 0, window=interior)#, anchor=Tkconstants.NW)
canvas.config(scrollregion=canvas.bbox("all"),width=200,height=200)
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
interior_id = canvas.create_window(0, 0, window=interior)#, anchor=Tkconstants.NW)
canvas.config(scrollregion=canvas.bbox("all"),width=200,height=200)
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
"""
一个有趣的注意事项是,mplCanvas
如果变大(如点击“较大”),将遵循大小调整 - 但如果变小则保持旧尺寸:
$ python2.7 test.py
(' Init', 'canvas.bbox:', (0, 0, 610, 610), 'mplCanvas.bbox:', (0, 0, 600, 600))
## here click "larger":
('old size is', array([ 4.06666667, 4.06666667]))
('new size is', array([ 6.1, 6.1]))
('new size pixels: ', 915.0, 915.0)
(' A', 'canvas.bbox:', (0, 0, 925, 925), 'mplCanvas.bbox:', (0, 0, 926, 926))
(' B', 'canvas.bbox:', (0, 0, 915, 915), 'mplCanvas.bbox:', (0, 0, 926, 926))
(' C', 'canvas.bbox:', (0, 0, 915, 915), 'mplCanvas.bbox:', (0, 0, 926, 926))
()
## here click "larger":
('old size is', array([ 6.1, 6.1]))
('new size is', array([ 9.15, 9.15]))
('new size pixels: ', 1372.4999999999998, 1372.4999999999998)
(' A', 'canvas.bbox:', (0, 0, 915, 915), 'mplCanvas.bbox:', (0, 0, 926, 926))
(' B', 'canvas.bbox:', (0, 0, 1372, 1372), 'mplCanvas.bbox:', (0, 0, 926, 926))
(' C', 'canvas.bbox:', (0, 0, 1372, 1372), 'mplCanvas.bbox:', (0, 0, 1372, 1372))
()
## here click "smaller":
('old size is', array([ 9.14666667, 9.14666667]))
('new size is', array([ 4.57333333, 4.57333333]))
('new size pixels: ', 686.0, 686.0)
(' A', 'canvas.bbox:', (0, 0, 1372, 1372), 'mplCanvas.bbox:', (0, 0, 1372, 1372))
(' B', 'canvas.bbox:', (0, 0, 686, 686), 'mplCanvas.bbox:', (0, 0, 1372, 1372))
(' C', 'canvas.bbox:', (0, 0, 686, 686), 'mplCanvas.bbox:', (0, 0, 1372, 1372))
()
在Python3.2中可以看到mplCanvas
的相同行为,以及......不确定这是否是各种错误,或者我也不理解正确的:)
另请注意,这种缩放方式不会处理轴/ tics等字体的大小调整(字体会尝试保持相同的大小);这是我最终可以使用上面的代码(截断的抽搐):
...如果添加轴标签等,情况会更糟。
无论如何,希望这会有所帮助,
干杯!