Skip to content Skip to sidebar Skip to footer

Python/tkinter: Update Button Text After Delay

I'm writing a simple little slapjack game to get acquainted with Python and Tkinter. I've got a button for the player to take their turn, but I'm stuck on how to get the computer t

Solution 1:

If I understand what you're asking, you might be looking for Tk.update(). If you call root.update() right before root.after(2000), this will do a force refresh and cause Tkinter to update the UI.

As an example (I modified your code):

from Tkinter import *

deck1 = ['A', 'B', 'C']
deck2 = ['D', 'E', 'F']
pile = []

defdeal():
    varTurn.get() % 2 == 0
    pile.append(deck1[0])
    deck1.remove(deck1[0])
    update_label()
    root.update()
    root.after(2000)
    pile.append(deck2[0])
    deck2.remove(deck2[0])
    update_label()


defupdate_label():
    varTurn.set(varTurn.get()+1)
    print(pile[len(pile)-1])
    varCard.set(pile[len(pile)-1])

root = Tk()
varCard = StringVar()
varTurn = IntVar()
lbl_btn = Button(root, textvariable=varCard, command=lambda: slap()).pack()
deal_btn = Button(root, text="deal", command=lambda: deal()).pack()
root.mainloop()

This causes the top button text to be refreshed immediately after the new card is drawn. Note that this ultimately might not be the best way to implement your game because even though the button updates to display the new card, the GUI will be unresponsive while waiting for the deal() function to complete.

Post a Comment for "Python/tkinter: Update Button Text After Delay"