Tkinter按钮保持按下状态

时间:2018-02-16 19:52:27

标签: python python-3.x button tkinter

我正在制作一个使用按钮小部件的代码tkinter但是当我按下按钮时,按钮一直按下,直到按下按钮的功能没有完成。我想在按下按钮时这样做,按钮将立即释放并执行其功能,它不应该卡住。 这是一个代码,它显示了一个很好的例子:

usage: sphinx-quickstart [OPTIONS] <PROJECT_DIR>
sphinx-quickstart: error: too few arguments

2 个答案:

答案 0 :(得分:2)

GUI程序在单个线程中被精简驱动,由主循环&#34;正在使用的图形工具包也就是说:程序通常设置应用程序,并将控制权传递给工具箱,该工具包运行一个紧密的循环来回答所有用户(以及netwrok,文件等等)事件,并且唯一可以再次运行的用户代码是在设置阶段编码的回调。

同时,当您的代码在回调期间运行时,它会保留控件 - 这意味着当您的函数未返回时,工具包无法回答任何事件。

必须要做的是编写与GUI工具包协作的代码 - 也就是说,如果需要时间间隔的话,创建生成进一步回调的事件。在tkinter的情况下,这是通过窗口小部件的方法.after实现的:在那么多毫秒之后,将运行传递的可调用对象。另一方面,time.sleep会停止那里的单个线程,并且事件循环不会运行。

在您的示例中,您只需编写:

from tkinter import *
import time
root = Tk()
root.geometry('100x100+100+100') # size/position of root

def callback(): # this function will run on button press
    print('Firing in 3')
    root.after(3000, realcallback)

def realcallback():
    print('Firing now!')

def main(): #function 'main'
    b = Button(root, text="ᖴIᖇE", width=10,height=2, command=callback)# setting the button
    b["background"] = 'red' #button color will be red
    b["activebackground"] = 'yellow'  #button color will be yellow for the time when the button will not be released
    b.place(x=25,y=25) #placing the button
main() # using function 'main'
mainloop()

答案 1 :(得分:0)

我想补充:

from tkinter import *
import time
root = Tk()
root.geometry('100x100+100+100') # size/position of root

def callback(): # this function will run on button press
    root.update() #<- this works for me..
    print('Firing in 3')
    root.after(3000, realcallback)

def realcallback():
    print('Firing now!')

def main(): #function 'main'
    b = Button(root, text="ᖴIᖇE", width=10,height=2, command=callback)# setting the  button
    b["background"] = 'red' #button color will be red
    b["activebackground"] = 'yellow'  #button color will be yellow for the time when the button will not be released
    b.place(x=25,y=25) #placing the button
main() # using function 'main'
mainloop()