create a tkinter windows with text in inside and ok exit button in python

Here's the code to create a tkinter window with text and an 'OK' button which closes the window when clicked:

main.py
import tkinter as tk

def close_window():
    root.destroy()

root = tk.Tk()

text_label = tk.Label(root, text="Sample Text")
text_label.pack()

button = tk.Button(root, text="OK", command=close_window)
button.pack()

root.mainloop()
234 chars
15 lines

In this code, we first import the tkinter library and define a function named close_window, which will destroy the window when called by the OK button.

Then, we create a Tk object and assign it to the root variable. This will be the main window of our app.

Next, we create a Label object and assign it to the text_label variable. We set the text of the label to "Sample Text", and then use the pack() method to place the label in the window.

After that, we create a Button object and assign it to the button variable. We set the text of the button to "OK" and then use the command option to assign the close_window function to the button so that it will be called when the button is clicked. We then use the pack() method to place the button beneath the label.

Finally, we start the event loop by calling the mainloop() method of the Tk object, which will display our window and wait for user interactions. When the OK button is clicked, the close_window() function is called which destroys the window and ends the program.

gistlibby LogSnag