我有一个Python脚本,它使用Tkinter作为GUI.我的小脚本应该每隔X秒创建一个Toplevel小部件.当我运行我的代码时,第一个Toplevel小部件成功创建,但当它尝试创建第二个时,程序崩溃.
我正在做的是使用after方法每隔5秒与root的mainloop一起调用函数startCounting.每次调用此函数时,我都会将Toplevel小部件对象附加到列表中并启动一个新线程,希望它将运行新的主循环.
如果有人能解决这个问题,我将非常感激.顺便说一下,这只是我目前用来解决我的问题的一个小脚本,这使我无法继续我的真实学校项目.
代码:
import threading,thread
from Tkinter import *
def startCounting():
global root
global topLevelList
global classInstance
topLevelList.append (Toplevel())
topLevelList[len(topLevelList)-1].title("Child")
classInstance.append(mainLoopThread(topLevelList[len(topLevelList)-1]))
root.after(5000,startCounting)
class mainLoopThread(threading.Thread):
def __init__(self,toplevelW):
self.toplevelW = toplevelW
threading.Thread.__init__(self)
self.start()
def run(self):
self.toplevelW.mainloop()
global classInstance
classInstance = []
global topLevelList
topLevelList = []
global root
root = Tk()
root.title("Main")
startCounting()
root.mainloop()
Run Code Online (Sandbox Code Playgroud) 我正在使用flask,matplotlib来保存图像和tensorflow来创建会话.我运行以下代码时遇到上述错误.烧瓶路线是否在单独的线程上运行?如何在主线程上运行fig.saveFig代码片段.非常感谢
@app.route('/open', methods = ['GET', 'POST'])
def sendOutput():
global loss,a2,xP,yP,scale,sess,fig
test_X,test_Y = own_model.getEvaluateData(scale)
cost,ans = sess.run([loss,a2],feed_dict={xP:test_X,yP:test_Y})
d = np.array(ans) - np.array(test_Y)
val = hist(d,100)
sess.close()
fig.saveFig('abc.png') //Errror on this line
Run Code Online (Sandbox Code Playgroud) 我编写了一个可以传递图像的简短模块,只需创建一个Tkinter窗口并显示它.我遇到的问题是,即使我实例化并调用在单独的线程中显示图像的方法,主程序也不会继续,直到Tkinter窗口关闭.
这是我的模块:
import Image, ImageTk
import Tkinter
class Viewer(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
def show(self,img):
self.to_display = ImageTk.PhotoImage(img)
self.label_image = Tkinter.Label(self,image=self.to_display)
self.label_image.grid(column = 0, row = 0, sticky = "NSEW")
self.mainloop()
Run Code Online (Sandbox Code Playgroud)
它似乎工作正常,除非我从我的测试程序中调用它,如下所示,它似乎不允许我的测试程序继续,即使在另一个线程中启动.
import Image
from viewer import Viewer
import threading
def showimage(im):
view = Viewer(None)
view.show(im)
if __name__ == "__main__":
im = Image.open("gaben.jpg")
t = threading.Thread(showimage(im))
t.start()
print "Program keeps going..."
Run Code Online (Sandbox Code Playgroud)
我想也许我的问题是我应该在模块本身内创建一个新线程,但我只想尝试保持简单,因为我是Python的新手.
无论如何,提前感谢任何帮助.
编辑:为了清楚起见,我只是想制作一个在Tkinter窗口中显示图像的模块,以便我可以在任何时候想要显示图像时使用该模块.我遇到的问题是,只要程序使用此模块,它就无法恢复,直到Tkinter窗口关闭.
我正在使用图形制作《谁想成为Python中的百万富翁游戏》。我希望用户每个问题有45秒的时间来回答。但是,每当我在代码中放置一个计时器时,它都会先等待45秒,然后让用户应答,而不是在后台运行并让用户同时应答。