Tkinter的。如何使用askopenfilename显示时钟/沙漏

时间:2013-11-15 16:19:02

标签: python tkinter

我正在使用Tkinter.askopenfilename打开包含外围设备登录详细信息的文件。我的代码获取这些详细信息,然后登录到该设备,通过CLI导航并从外围设备下载配置映像。

此过程可能需要10到15秒,我想在此期间更改光标状态。我发现如果我尝试打开一个新窗口来显示正在进行的消息,则在显示对话框之前完成下载。

示例代码片段:

 filename = askopenfilename(parent=root,filetypes=[("Configured Devices",".cfg")])
 if len(filename) == 0:
    return
 file_list = open(filename,'r')
 for line in file_list:
    line=line.strip()
    line=line.split(",")
    ip=line[0]
    username = line[1]
    password = line[2]
    break
 file_list.close()
 get_config(ip,username,password)  #This logs in and extracts the configuration

2 个答案:

答案 0 :(得分:1)

我为同样的事情而苦苦挣扎。找不到我喜欢且似乎完整的答案。所以这是我整理的一个示例:

import tkinter as Tk
import time


class AppWaitCursor(  ):
    """
    Purpose:
        display wait cursor, continue with a blocking task
        and restore cursor
        Here: task is a sleep and print

    This is a bit of a pain as we need 2 methods to implement, could get cleverer
    passing around functions, perhaps closures, partials, or lambdas, that would
    obscure the technique.

    Got something better for the same purpose?  Let me know.

    works but not reliably inside of spyder --
    run from command line
    only tried in windows python 3.8
    """

    #  ----------- init -----------
    def __init__( self,     ):
        self.build_run()      # separate method for easier messing about

# ------------------------------------------
def begin_wait_cursor_task( self,  ):
    """
    this really just sets up the cursor, then calls the rest of the task
    """
    self.root.config( cursor="wait" )   # but not displayed need a refresh
    print( "begin_wait_cursor_task", flush = True)

    # time in ms 20 seems good 2 not so much, idle did not do it for me:
    # this may give the user 20 ms to interact with gui but most will not notice
    # click twice fast and it may then run twice!
    self.root.after( 20 ,     self.continue_wait_cursor_task  )


# ------------------------------------------
def continue_wait_cursor_task( self ):
    """
    """
    print( "continue_wait_cursor_task", flush = True)
    time.sleep( 1 )
    print( "almost there" )
    time.sleep( 1 )
    self.root.config( cursor="" )
    print( "normal cursor\n\n", flush = True)


# ----------------------------------------
def build_run( self):
    """
    build the gui and run it

    """
    self.root       = Tk.Tk()

    a_widget  = Tk.Button( self.root, text="do wait cursor task",     command = self.begin_wait_cursor_task )
    a_widget.pack()

    a_widget  = Tk.Button( self.root, text="do nothing",   )
    a_widget.pack()



    self.root.mainloop()


def ex_cursor0():
    print( """
    ------------------ ex_cursor0 ----------------
    """ )
    app     = AppWaitCursor( )


ex_cursor0()

    enter code here

答案 1 :(得分:0)

您需要使用root.config(cursor="wait")将光标更改为忙碌光标。