我只有一个while循环而Tkonter说:GUI没有响应。 我做错了什么?我想用按钮“暂停”休息和 再次使用“按钮”开始“继续程序。
import Tkinter, time
root = Tkinter.Tk
class InterfaceApp(root):
def __init__ (self, parent):
root.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.but_state = 0
self.but_start = Tkinter.Button(self, text='Start', command=lambda: self.Start(), width=10)
self.but_pause = Tkinter.Button(self, text="Pause", command=lambda: self.Pause(), width=10)
self.but_stop = Tkinter.Button(self, text='Stop', command=lambda: self.Stop(), width=10)
self.but_start.grid(row=1, column=1, sticky='W')
self.but_pause.grid(row=1, column=2, sticky='W')
self.but_stop.grid(row=1, column=3, sticky='W')
def Start(self):
while True:
print "X"
time.sleep(2)
if self.but_state == 1:
break
else:
continue
def Stop(self):
self.but_state = 1
def Pause(self):
pass
if __name__ == "__main__":
app = InterfaceApp(None)
app.title("MPW4 microHP - Long Term Test")
app.mainloop()
答案 0 :(得分:3)
使用while循环。在完成使用后再次调用函数
self.after(<time in ms>, <function to call>)
在def Start(self)
看起来像这样:
# ...
def Start(self):
print("X")
if self.but_state == 0:
self.after(2000, self.Start)
# ...
不要将lambda用于简单的调用。使用绑定的名称,就像@Parviz_Karimli指出的那样。
def initialize(self):
self.but_state = 0
self.but_start = Tkinter.Button(self, text='Start', command=self.Start, width=10)
self.but_pause = Tkinter.Button(self, text="Pause", command=self.Pause, width=10)
self.but_stop = Tkinter.Button(self, text='Stop', command=self.Stop, width=10)
self.but_start.grid(row=1, column=1, sticky='W')
self.but_pause.grid(row=1, column=2, sticky='W')
self.but_stop.grid(row=1, column=3, sticky='W')
答案 1 :(得分:1)
你的代码是无稽之谈。你必须弄清楚如何定义函数并首先正确使用它们。我为你写了一个小例子:
from tkinter import *
class App:
def __init__(self, master):
self.master = master
self.startb = Button(master, text="Start", command=self.startf)
self.startb.pack()
self.pauseb = Button(master, text="Pause", command=self.pausef)
self.pauseb.pack()
self.stopb = Button(master, text="Stop", command=self.stopf)
self.stopb.pack()
def startf(self):
print("Started")
self.after_id = self.master.after(1000, self.startf)
def pausef(self):
if self.startf is not None: # to handle any exception
self.master.after_cancel(self.after_id) # this will pause startf function -- you can start again
print("Paused")
def stopf(self):
if self.startf is not None:
self.master.after_cancel(self.after_id)
self.startf = None # this will stop startf function -- you cannot start again
print("Stopped")
root = Tk()
myapp = App(root)
root.mainloop()
然后你可以修改这段代码 - 更改函数的行为等。如果你有一段代码,它将表现为&#34; motor&#34;执行程序核心思想的函数,也包含该函数,并在startf
函数中返回它,将其暂停在pausef
函数中,最后在{{1}中停止它功能。
P.S。:我的代码是用 Python 3 编写的
编辑:我完成了代码,上面是一个工作程序,根据您点击的按钮启动,暂停和停止。