I want to ask that if I click on a button, then it perform a command and if I click again on the button then it perform another command. Basically I have two commands which I want to use in loop.
#Import tkinter here
from tkinter import *
#defining root function.
root = Tk()
root.geometry('200x100')
#define fuction for labelA
def funcA():
labelA["text"] = "A responds"
#define fuction for labelB
def funcB():
labelB["text"] = "B responds"
#Define button.
button = Button(root, text = 'Click Me', command=lambda:[funcA(), funcB()])
button.pack()
#creating both label A and B
labelA = Label(root, text="A")
labelB = Label(root, text="B")
labelA.pack()
labelB.pack()
root.mainloop()
In this code when I click on button, both the function run at same time. But I want that when i click on the button, the first function should run and if I click again on button then run second function. This will be in loop (like first of all first label will update then second label will update then again first label update then again second label).
CodePudding user response:
i think you can save the button inside a variable and when function1 run after execution set command
attribute to function2 and after function2 executed set command
to function1
CodePudding user response:
You should have a bool value tracking if the button has been pressed or not. You can change this value in your functions as well.
somebool = False
#define fuction for labelA
def funcA():
if somebool:
labelA["text"] = "A responds"
#define fuction for labelB
def funcB():
if !somebool:
labelB["text"] = "B responds"
Note that this approach is not good if you want to access one function alone from another button. If you have a bool state like this though, you do not need 2 separate functions. You can make an event handler for the button and then call funcA or funcB from there.
somebool = False
def handler():
funcA() if somebool else funcB()
def funcA():
labelA["text"] = "A responds"
def funcB():
labelB["text"] = "B responds"
button = Button(root, text = 'Click Me', command=handler)
If you don't care about reusing the functions, change the command attribute for the button in your function to run the other one.