2017-06-02 206 views
-1

我該如何避免這種情況?while True Loop。我必須運行def func(i)無限次。避免這種循環的原因是,無論何時我創建兩個類,一個類有這段代碼,另一個類有一個按鈕來訪問這段代碼時,按下按鈕,但我得到的問題是,我不能將這個matplotlib集成在tkinter窗口中。該按鈕單獨顯示,matplotlib單獨運行。但是,當我刪除while循環,然後它以某種方式解決了這個問題,但沒有無限循環。如何避免infinte循環

import matplotlib 
matplotlib.use("TkAgg") 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 
import matplotlib.pyplot as plt 
import numpy as np 
import tkinter as tk 
from tkinter import * 
import matplotlib.animation as animation 

j=0 
fig = plt.figure() 
ax1 = fig.add_axes([0.85, 0.093, 0.04, 0.8]) 
cax = fig.add_subplot(1, 1, 1) 

H = np.array([[1, 2, 3, 1], [4, 5, 6, 10], [3, 7, 8, 4], [10, 5, 3, 1]]) 
Z = np.array([[3, 290, 600], [1011, 230, 830], [152, 750, 5]]) 

while True: 
    def func(i): 
     global j 
     if j == 0: 
      j += 1 
      rows, cols = H.shape 

      im = plt.imshow(H, interpolation='nearest', 
          extent=[0, cols, 0, rows], 
          cmap='bwr', vmin=0, vmax=10) 
      fig.colorbar(im, cax=ax1, orientation='vertical') 


     elif j == 1: 

      j -= 1 
      rows, cols = H.shape 

      im = plt.imshow(Z, interpolation='nearest', cmap='Spectral', vmin=0, vmax=1023,extent=[0, cols, 0, rows]) 
      v = np.linspace(0, 1023, 15, endpoint=True) 
      fig.colorbar(im, cax=ax1, orientation='vertical', ticks=v) 


    ani = animation.FuncAnimation(fig, func, interval=1000) 
    plt.show() 
    plt.close() 
+7

我不明白你爲什麼要一遍又一遍地定義一個函數,看起來像一個大錯誤的設計給我。你能否更廣泛地解釋你想完成什麼? –

+0

此外,代碼中沒有按鈕。不過看起來按鈕是在while循環中使用動畫循環結構的原因。但是由於我們不知道按鈕的問題,所以在這裏不可能提供幫助。從你所說的話,「我不能將這個matplotlib集成到tkinter窗口中」似乎是**真正的問題**,並且詢問這個問題而不是其他問題可能是有意義的。 – ImportanceOfBeingErnest

+0

@alec_djinn我的老師給我的任務是建立數組並使用matplotlib一次又一次地顯示它們。然後我必須將matplotlib集成到tkinter中。 –

回答

1

代碼風格:你能避免運行def反覆而不是定義爲第j == 1例兩種功能,func0(i)爲第j == 0的情況和func1(i)? (我假設func必須有一個預定義的簽名,並作爲參數傳遞給它,你不能添加J任務。)然後無限循環的身體改變

ani = animation.FuncAnimation(fig, func0, interval=1000) 
plt.show() 
plt.close() 
ani = animation.FuncAnimation(fig, func1, interval=1000) 
plt.show() 
plt.close() 

使用定時器或一個線程而不是 :在GUI應用程序中有無限循環是一個壞主意,至少在處理事件的線程中。你可以把無限循環放到一個單獨的線程中嗎(注意,線程不適合膽怯的人)或將它改變爲重複的定時器驅動事件(事件中沒有循環)?

更多關於定時器:這個想法是使用一個計時器來運行一個循環,然後返回到GUI,以便它得到更新和響應。 Tkinter使用根窗口的after()方法支持定時器。我不知道它是否支持重複計時器,但您所要做的只是在計時器事件結束時重新啓動計時器。

How to create a timer using tkinter?,How to create a timer using tkinter?Python - Countdown timer within a tkinter canvas中有一些例子。

(對不起,我更願意將其添加爲註釋,但I don't have enough reputation here

+0

謝謝你的回答。如果我不使用循環,我怎樣才能一次又一次地調用一個函數?請記住,我必須將matplotlib集成到tkinter窗口中,以實現GUI設計。 –

+0

編輯我的答案與一些更多的解釋和一些例子的鏈接,希望幫助 –

+0

@JoeP也許你開始回答**可以**回答的問題,而不是試圖回答太不清楚的問題。這將允許你很容易地獲得所需的聲望評論(只有兩個upvotes我猜)。像這樣的不清楚的問題應該沒有答案,這樣提問者被迫編輯它並且更加清楚,而不是在答案下面開始討論,這實際上不是一個答案。 – ImportanceOfBeingErnest