Interaction between button in Python Tkinter [closed]

Tags: ,

I’m trying to create a simple Tkinter GUI using Python. The user interface has 3 different buttons: Yes, No and Print.

If the user click button Yes then click button Print, a line will appear “Yes is 1” in the user interface.

If the user un-click Yes, then “No”, then click Print, a line will appear “No is 0” in the user interface

If user only click Yes, nothing will be shown.

But how can the program can know which button the user click? Which function can I use to find the connection between these two related button? How the code is performed?

Thank you so much!


Are you looking for something like this?:

import tkinter as tk

text_to_be_printed = None

def yes_pressed():
    global text_to_be_printed
    text_to_be_printed = "yes"

def no_pressed():
    global text_to_be_printed
    text_to_be_printed = "no"

def print_pressed():
    # If you want to print the text to the console:
    # print(text_to_be_printed)

root = tk.Tk()

results_label = tk.Label(root, text="")

yes_button = tk.Button(root, text="yes", command=yes_pressed)
no_button = tk.Button(root, text="no", command=no_pressed)
print_button = tk.Button(root, text="print", command=print_pressed)



It uses 3 functions that are called when the corresponding button is pressed. It also uses a flag text_to_be_printed that contains the data that should be printed on the screen. Please note that it is a global variable.

Source: stackoverflow