python
  • tkinter
  • 2015-01-06 58 views 0 likes 
    0

    我已經搜索過,並嘗試在我的應用程序中使用Tkinter中的.after命令,但我沒有做任何解決此問題的方法。無論我嘗試做什麼,我試圖拖延的兩個盒子同時出現。無法獲取.after命令在Tkinter中工作

    submenu.add_command(label="View High Score", command=lambda: check_hs_file()) 
    
    def check_hs_file(): 
        hs_file = 'highscore.txt' 
        PATH = ('highscore.txt') 
        if os.path.isfile(PATH): 
         get_hs_as_int() 
         #go to main function 
        else: 
         with open(hs_file, 'w') as hs_file: 
          hs_file.write('0') 
         if os.path.isfile(PATH): 
          toplevel1 = Toplevel() 
          toplevel1.title("High Score!") 
          toplevel1.focus_set() 
          hs_textbox = Text(toplevel1, height=2, width=50) 
          hs_textbox.pack() 
          hs_textbox.insert(END, "You don't have a high score yet.. Creating file!\n") 
          get_hs_as_int() 
         else: 
          toplevel = Toplevel() 
          toplevel.title("High Score!") 
          toplevel.focus_set() 
          hs_textbox = Text(toplevel, height=2, width=50) 
          hs_textbox.pack() 
          hs_textbox.after(3000) 
          hs_textbox.insert(END, "Something went wrong, we could not create a file to keep your high score!") 
    
    def get_hs_as_int(): 
        hs_file = 'highscore.txt' 
        with open(hs_file, 'r') as hs_file: 
         high_score = hs_file.read() 
         high_score = int(high_score) 
        toplevel = Toplevel() 
        toplevel.after(4000) 
        toplevel.title("High Score!") 
        toplevel.focus_set() 
        hs_textbox = Text(toplevel, height=2, width=50) 
        hs_textbox.pack() 
        hs_textbox.insert(END, "Your high score is: {}".format(high_score)) 
    

    再次,打印高分的盒子,以及查看是否有高分的一個盒子同時出現。無論我在何處添加.after在我的代碼之後。任何幫助真的會很感激!

    +0

    它很難對代碼進行測試,因爲這取決於許多文件,等等。一些展示問題核心的虛擬簡單代碼會很有用,這樣我們就可以運行它,測試它,修改它並希望能夠提供答案。 – Marcin

    +0

    請閱讀http://stackoverflow.com/help/mcve。 –

    回答

    0

    Tk.Widget.after的通常語法將回調函數作爲參數。

    所以,用一個小片段作爲一個例子,你可以寫:

    def method(...): 
        ... # calculate the meaning of life 
    
        def callback(): 
         print("I'm called later!") 
    
        self.after(10, callback) # execute callback() after 10s 
    

    更常見的是,你要做的就是定義在類或模塊的另一個函數或方法,然後通過在指定時間後關閉。

    因此,舉例來說,如果你想在短期內出現在窗口之後顯示一個彈出,你可以這樣做:

    class Controller(): 
        def __init__(self, master): 
         # perform some initial setup 
    
         master.after(5, self.finalise) # run self.finalise() after 5s 
    
         # do some more setup 
    
        def finalise(self): 
         tk.messagebox.showinfo('Called later', 'Yippeeeeeee!') 
    
    相關問題