create a button in a tkinter window to activate a function in python

To create a button in a tkinter window that activates a function in Python, you can follow these steps:

  1. Import the tkinter module:
main.py
import tkinter as tk
21 chars
2 lines
  1. Create a function that will be executed when the button is clicked:
main.py
def my_function():
    # do something
38 chars
3 lines
  1. Create an instance of the tkinter window:
main.py
root = tk.Tk()
15 chars
2 lines
  1. Create a button widget and specify its properties, including the text displayed on the button and the function to be called when the button is clicked:
main.py
button = tk.Button(root, text="Click me", command=my_function)
63 chars
2 lines

Note that the "command" option is set to the name of the function you defined earlier.

  1. Optionally, you can pack or place the button widget in the tkinter window:
main.py
button.pack()
14 chars
2 lines

or

main.py
button.place(x=50, y=50)
25 chars
2 lines
  1. Finally, start the main tkinter event loop to display the window and enable user interaction:
main.py
root.mainloop()
16 chars
2 lines

Here's the complete code block to create a button in a tkinter window that activates a function in Python:

main.py
import tkinter as tk

def my_function():
    print("Button clicked!")

root = tk.Tk()

button = tk.Button(root, text="Click me", command=my_function)
button.pack()

root.mainloop()
181 chars
12 lines

gistlibby LogSnag