简体   繁体   中英

Tkinter: change text in a label multiple times in a series using a single button

I have this quick example here:

from tkinter import *

root = Tk()

display = Label(root,text="Starting")
display.pack()

def change(): #Do on first press of button
    global display
    display.config(text="I just changed")

def change1(): #Do on second press of button
    global display
    display.config(text="I changed again")

def change2(): #Do on third press of button
    global display
    display.config(text="I changed once more")

button = Button(root,text="Press me",command=change)
button.pack()

It obviously changes the label saying "Starting" to "I just changed" on the first press of the button, but how would I make it do the other two functions (change1 and change2) on successive presses of the same button?

You can set a counter to determine what to change the label text to and then when the counter reaches it's maximum reset it to handle further button presses. You actually don't need global to change the label here.

from tkinter import *

root = Tk()

display = Label(root,text="Starting")
display.pack()

def _change():

    if button.counter == 0:
        display.config(text="I just changed")
    elif button.counter == 1:
        display.config(text="I changed again")
    else:
        display.config(text="I changed once more")
    if button.counter != 2:
        button.counter += 1
    else:
        button.counter = 0

button = Button(root,text="Press me",command=_change)
button.counter = 0
button.pack()
root.mainloop()

To do that you have to define a variable to keep track of which time the button has been pressed. You also have to make an update function to increase the variable and test the state of the variable.

For example:

from tkinter import *

root = Tk()

display = Label(root,text="Starting")
displayState = 1
display.pack()

def change():
    global displayState, display

    if displayState == 1:
        display.config(text="I just changed")

    elif displayState == 2:
        display.config(text="I changed again")

    elif displayState == 3:
        display.config(text="I changed once more")

    displayState += 1

button = Button(root,text="Press me",command=change)
button.pack()

root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM