简体   繁体   中英

how to check if button is clicked on tkinter

I am trying to create a car configurator using tkinter as a gui in my free time.

I have managed to open a tkinter box with images that act as buttons.

What I want to do is for the user to click on a button. I want to check which button has been clicked (ie if the family car button is clicked, how can I check that it has been clicked).

I have done my research on this website, and all of the solutions I have found have been in javascript or other languages.

Once the button has been clicked, I want a new window to be opened ONLY containing attributes for a family car i.ea family car can have a red exterior colour, but a sports car cannot have a red exterior colour at all.

Here is my code below:

from tkinter import *
import tkinter as tk

def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()

familycar = PhotoImage(file = "VW family car.png")
familylabel = Button(root, image=familycar)
familybutton = Button(root, image=familycar, command=create_window)

familybutton.pack()

So how can I check that the family car button has been clicked?

Thanks

Use a Boolean flag.

Define isClicked as False near the beginning of your code, and then set isClicked as True in your create_window() function.

This way, other functions and variables in your code can see whether the button's been clicked ( if isClicked ).

Not sure what you asked, do you want to disable it or check its status in another routine ? Or just to count the times it has been clicked,

In order to do that Simple solution would be to add a general variable that will be updated inside the create_window method (general because you want to allow access from other places).

First, you would need to initialize a function in which you want to execute on the button click.

example:

def button_clicked():
    print('I got clicked')

Then, when you define the target button, you'll have to set the 'command' argument to the required function(the button_clicked function in this context).

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