tkinter 和 matplotlib:在 Linux 下程序关闭之前不会显示窗口
Posted
技术标签:
【中文标题】tkinter 和 matplotlib:在 Linux 下程序关闭之前不会显示窗口【英文标题】:tkinter and matplotlib: windows not showing until program closes under Linux 【发布时间】:2014-11-04 05:21:40 【问题描述】:我编写了一个程序,该程序基本上在按下不同按钮时绘制不同的数据。该程序在 Windows 下按预期工作,但是当我尝试将其移植到 Linux(Red Hat v6)时,我遇到了一个奇怪的问题:我要绘制的窗口直到我关闭主程序后才会出现。无论我尝试绘制的图形(图 1,2 等)如何,或者我尝试输入 plt.show() 等,都会发生这种情况。
我写的程序差不多有 1000 行代码,但是我创建了一个有同样问题的缩写程序。它可以在 Windows 下运行,但在 Linux 下我必须关闭根窗口才能显示 matplotlib 窗口。
工作代码:
import matplotlib.pyplot as plt
from tkinter import *
def click():
x=['0','1','2']
plt.plot(x,x)
plotGUI=Tk()
butt1=Button(plotGUI,text="Test", command=click).grid()
plotGUI.mainloop()
【问题讨论】:
【参考方案1】:如果精简后的代码仍然没有出现Tk-toplevel窗口,添加一行:
plotGUI.lift() # force WM to raise Tk() window
plotGUI.mainloop()
如果精简代码在matplotlib
-wrapper 方面存在问题,则有必要更具体地说明您使用什么包装方法将matplitlib
-output 放入Tkinter Canvas 等.
如果代码试图依赖默认的matplotlib
工具plt.show()
,那么代码将受到两个相邻 .mainloop()
-s的影响——首先Tk()
's -- 第二个隐藏在默认 matplotlib
-s .show()
-- 因此你的代码将变得难以控制两个相邻的 UI-s。
协同集成的用户界面
为了拥有不相邻的 UI 控制器和协同集成 UI 的更多好处,
尝试重新使用 后端 工厂直接在 Tkinter.Canvas
和您选择和控制的其他可能的小部件上绘图。
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
并继续在您的代码和 matplotlib 模型状态/输入控制器/视觉输出上的 both 上完全集成 GUI-MVC 层。
共同集成 UI 示例的更多代码:
class SuperShapeFrame( Frame ): # The user interface:
def __init__( self, master = None ):
Frame.__init__( self, master )
self.grid()
self.m = 3
self.n1 = 2
self.n1_scaling = LinearScaling( ( .1, 20 ), ( 0, 200 ) )
self.n2 = 18
self.n2_scaling = LinearScaling( ( .1, 20 ), ( 0, 200 ) )
self.n3 = 18
self.n3_scaling = LinearScaling( ( .1, 20 ), ( 0, 200 ) )
self.fig = Figure( ( 6, 6 ), dpi = 100 )
canvas = FigureCanvasTkAgg( self.fig, master = self )
canvas.get_tk_widget().grid( row = 0, column = 0, columnspan = 4 )
label = Label( self, text = 'M' )
label.grid( row = 1, column = 1 )
self.m_slider = Scale( self, from_ = 1, to = 20, \
orient = HORIZONTAL, command = lambda i : self.update_m() \
)
self.m_slider.grid( row = 1, column = 2 )
label = Label( self, text = 'N1' )
label.grid( row = 2, column = 1 )
self.n1_slider = Scale( self, from_ = 0, to = 200, \
orient = HORIZONTAL, command = lambda i : self.update_n1() \
)
self.n1_slider.grid( row = 2, column = 2 )
label = Label( self, text = 'N2' )
label.grid( row = 3, column = 1 )
self.n2_slider = Scale( self, from_ = 0, to = 200, \
orient = HORIZONTAL, command = lambda i : self.update_n2() \
)
self.n2_slider.grid( row = 3, column = 2 )
label = Label( self, text = 'N3' )
label.grid( row = 4, column = 1 )
self.n3_slider = Scale( self, from_ = 0, to = 200,
orient = HORIZONTAL, command = lambda i : self.update_n3() \
)
self.n3_slider.grid( row = 4, column = 2 )
self.draw_figure() # >>> ================================================================ DRAW FIRST APPEARANCE OF THE INSTANCE
def update_m( self ):
self.m = self.m_slider.get()
self.refresh_figure() # >>> .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE
def update_n1( self ):
self.n1 = self.n1_scaling.dst_to_src( self.n1_slider.get() )
self.refresh_figure() # >>> .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE
def update_n2( self ):
self.n2 = self.n2_scaling.dst_to_src( self.n2_slider.get() )
self.refresh_figure() # >>> .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE
def update_n3(self):
self.n3 = self.n3_scaling.dst_to_src( self.n3_slider.get() )
self.refresh_figure() # >>> .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE
def refresh_figure( self ): # <<< .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE ACTUAL APPEARANCE OF THE INSTANCE
r = supershape_radius( self.phi, 1, 1, self.m, self.n1, self.n2, self.n3 ) # .CALC new polar values in radius dimension
self.lines.set_ydata( r ) # .MOD <lines>, selectively just their <lines>.set_ydata() coordinates
self.fig.canvas.draw_idle() # .GUI MVC-Visual part UPDATE via <self>.<fig>.<canvas>.draw_idle()
def draw_figure( self ): # <<< =============================================================== DRAW FIRST APPEARANCE OF THE INSTANCE
self.phi = np.linspace( 0, 2 * np.pi, 1024 ) # .STO <phi> a np.array with static fi-coordinates
r = supershape_radius( self.phi, 1, 1, self.m, self.n1, self.n2, self.n3 )
ax = self.fig.add_subplot( 111, polar = True ) #
self.lines, = ax.plot( self.phi, r, lw = 3. ) # .STO <lines> aListOfLINEs from .plot() function
self.fig.canvas.draw() # .GUI MVC-Visual part, enforce first visual output via <self>.<fig>.<canvas>.draw()
def TkDemo(): # Finally, we set up and start our user interface:
""" HELP: CookBook: Tk-GUI-MVC via SuperShape example
TESTS: TkDemo()
"""
root = Tk()
root.lift()
root.protocol( 'WM_DELETE_WINDOW', root.quit() ) # [X]-overide ---------------------------
app = SuperShapeFrame( root ) # <<<--- pass <root>
app.master.title( 'CookBook: Tk-GUI-MVC via SuperShape' )
app.mainloop()
pass
[Halldinz0r] 复制/粘贴按原样重新测试的完整代码:
####################################################################### #
###
### TkDemo()
###
### KCA_plot_inTk ##################################################### # Tk() GUI ###################################################################################################### _plot_inTk TkDemo() #################
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
def supershape_radius( phi, a, b, m, n1, n2, n3 ): # define the function for the SuperShape curve using the following code:
theta = .25 * m * phi
cos = np.fabs( np.cos( theta ) / a ) ** n2
sin = np.fabs( np.sin( theta ) / b ) ** n3
r = ( cos + sin ) ** ( -1. / n1 )
r /= np.max( r )
return r
class LinearScaling( object ): # define a utility object to linearly scale a range into another as follows:
def __init__( self, src_range, dst_range ):
self.src_start, src_diff = src_range[0], src_range[1] - src_range[0]
self.dst_start, dst_diff = dst_range[0], dst_range[1] - dst_range[0]
self.src_to_dst_coeff = dst_diff / src_diff
self.dst_to_src_coeff = src_diff / dst_diff
def src_to_dst( self, X ):
return ( X - self.src_start ) * self.src_to_dst_coeff + self.dst_start
def dst_to_src( self, X ):
return ( X - self.dst_start) * self.dst_to_src_coeff + self.src_start
class SuperShapeFrame( Frame ): # The user interface:
def __init__( self, master = None ):
Frame.__init__( self, master )
self.grid()
self.m = 3
self.n1 = 2
self.n1_scaling = LinearScaling( ( .1, 20 ), ( 0, 200 ) )
self.n2 = 18
self.n2_scaling = LinearScaling( ( .1, 20 ), ( 0, 200 ) )
self.n3 = 18
self.n3_scaling = LinearScaling( ( .1, 20 ), ( 0, 200 ) )
self.fig = Figure( ( 6, 6 ), dpi = 100 )
canvas = FigureCanvasTkAgg( self.fig, master = self )
canvas.get_tk_widget().grid( row = 0, column = 0, columnspan = 4 )
label = Label( self, text = 'M' )
label.grid( row = 1, column = 1 )
self.m_slider = Scale( self, from_ = 1, to = 20, \
orient = HORIZONTAL, command = lambda i : self.update_m() \
)
self.m_slider.grid( row = 1, column = 2 )
label = Label( self, text = 'N1' )
label.grid( row = 2, column = 1 )
self.n1_slider = Scale( self, from_ = 0, to = 200, \
orient = HORIZONTAL, command = lambda i : self.update_n1() \
)
self.n1_slider.grid( row = 2, column = 2 )
label = Label( self, text = 'N2' )
label.grid( row = 3, column = 1 )
self.n2_slider = Scale( self, from_ = 0, to = 200, \
orient = HORIZONTAL, command = lambda i : self.update_n2() \
)
self.n2_slider.grid( row = 3, column = 2 )
label = Label( self, text = 'N3' )
label.grid( row = 4, column = 1 )
self.n3_slider = Scale( self, from_ = 0, to = 200,
orient = HORIZONTAL, command = lambda i : self.update_n3() \
)
self.n3_slider.grid( row = 4, column = 2 )
self.draw_figure() # >>> ================================================================ DRAW FIRST APPEARANCE OF THE INSTANCE
def update_m( self ):
self.m = self.m_slider.get()
self.refresh_figure() # >>> .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE
def update_n1( self ):
self.n1 = self.n1_scaling.dst_to_src( self.n1_slider.get() )
self.refresh_figure() # >>> .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE
def update_n2( self ):
self.n2 = self.n2_scaling.dst_to_src( self.n2_slider.get() )
self.refresh_figure() # >>> .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE
def update_n3(self):
self.n3 = self.n3_scaling.dst_to_src( self.n3_slider.get() )
self.refresh_figure() # >>> .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE
def refresh_figure( self ): # <<< .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. UPDATE ACTUAL APPEARANCE OF THE INSTANCE
r = supershape_radius( self.phi, 1, 1, self.m, self.n1, self.n2, self.n3 ) # .CALC new polar values in radius dimension
self.lines.set_ydata( r ) # .MOD <lines>, selectively just their <lines>.set_ydata() coordinates
self.fig.canvas.draw_idle() # .GUI MVC-Visual part UPDATE via <self>.<fig>.<canvas>.draw_idle()
def draw_figure( self ): # <<< =============================================================== DRAW FIRST APPEARANCE OF THE INSTANCE
self.phi = np.linspace( 0, 2 * np.pi, 1024 ) # .STO <phi> a np.array with static fi-coordinates
r = supershape_radius( self.phi, 1, 1, self.m, self.n1, self.n2, self.n3 )
ax = self.fig.add_subplot( 111, polar = True ) #
self.lines, = ax.plot( self.phi, r, lw = 3. ) # .STO <lines> aListOfLINEs from .plot() function
self.fig.canvas.draw() # .GUI MVC-Visual part, enforce first visual output via <self>.<fig>.<canvas>.draw()
def TkDemo(): # Finally, set up and start our user interface:
""" HELP: CookBook: Tk-GUI-MVC via SuperShape example
TESTS: TkDemo()
"""
root = Tk()
root.lift()
root.protocol( 'WM_DELETE_WINDOW', root.quit() ) # [X]-overide ---------------------------
app = SuperShapeFrame( root ) # <<<--- pass <root>
app.master.title( 'CookBook: Tk-GUI-MVC via SuperShape' )
app.mainloop()
pass
### ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ _plot_inTk TkDemo() ^^^^^^^^^^^^^^^^^^
【讨论】:
感谢 user3666197 的回复。但是,这两个例子都不适合我。我通过使用 lift() 遇到了与以前相同的问题,并且您提供的 GUI-MVC 代码运行时没有任何错误,但根本没有出现 GUI。 @Halldinz0r 发布示例是为了说明matplotlib
-output 集成对Tkinter Canvas
,而不是作为一个独立的应用。将在下面发布整个代码(^ 以上)。如果没有显示,我们开始。【参考方案2】:
我只需添加以下内容即可使其工作:
matplotlib.use('TkAgg')
这使得程序就像在 Windows 中一样工作,无需任何其他修改。不过,我真的需要学习 user3666197 发布的概念以用于未来的项目。
【讨论】:
谢谢,它说我必须等待一天才能接受我自己的答案。现在它说 8 小时。以上是关于tkinter 和 matplotlib:在 Linux 下程序关闭之前不会显示窗口的主要内容,如果未能解决你的问题,请参考以下文章
使用 matplotlib 在 Tkinter 中绘制数据 - 在列表之间切换
需要帮助使用matplotlib在tkinter中绘制图形[重复]
tkinter 和 matplotlib:在 Linux 下程序关闭之前不会显示窗口