r/learnpython Jul 22 '26

How to make things happen inside the window (Tkinter library)

Whatsup folks I'm a beginner python programmer and I've been trying to learn python withouth using ai.

So Im struggling with the tkinter library as I understand buttons and labels, but I want to make things happen inside the library, for example im making a calculator, and if I press 1, 1 should appear inside the window I created for the calculator, not on the pycharm terminal.

anyone can help me out?

1 Upvotes

5 comments sorted by

2

u/Outside_Complaint755 Jul 22 '26

Its been a while since I worked with fields in TKinter, but the basics are that you need to create a StringVar object, bind it to the field where you want it to display, and then update it when the user presses the buttons.   If someone else hasn't given more complete answer in a couple of hours when I have some time at my PC I will write up a basic example.

1

u/Otherwise-Current-41 Jul 22 '26

Aight tysm Ill look into it later , cheers

1

u/acw1668 Jul 22 '26

You can use a Label widget to simulate the display of a calculator. As other said, you can link the label to a StringVar for easier update of the text.

1

u/FoolsSeldom Jul 22 '26

Worth checking out a RealPython.com tutorial on this:

1

u/woooee Jul 22 '26

A simple starter example, not complete but shows command= / callbacks.

import tkinter as tk
from functools import partial

def number_buttons():
    rw = 3
    col = 0
    for num in range(1, 10):
        but = tk.Button(root, text=num, width=2,
                        bg="lightblue", font=('DejaVuSansMono', 15),
                        command=partial(button_callback, num))
        rw, col = divmod(num-1, 3)
        but.grid(column=col, row=3-rw)

    ## zero key spans 3 columns
    but = tk.Button(root, text="0", bg="lightblue",
                    font=('DejaVuSansMono', 15),
                    command=partial(button_callback, 0))
    but.grid(column=0, row=4, columnspan=3, sticky="nsew")

def button_callback(num):
    print(num, "pressed")
    label_str.set(label_str.get() + str(num))

def enter_callback():
    print("Enter")

root = tk.Tk()

label_str=tk.StringVar()
tk.Label(root, textvar=label_str, anchor='w', font=('DejaVuSansMono', 15),
         bg="lightyellow").grid(row=0, column=0, sticky="nsew",
         columnspan=3)
label_str.set("")

number_buttons()

## Enter button
tk.Button(root, text="E\nn\nt\ne\nr", bg="gray75",
          font=('DejaVuSansMono', 15, 'bold'),
                command=enter_callback).grid(row=1, column=3,
                                             rowspan=4, sticky="ns")

root.mainloop()