i need to make this for 6 buttons...

If each button modifies the same global variable, then have make_something accept a value parameter:

from tkinter import Tk, Button
variable = 1
def make_something(value):
    global variable
    variable = value
root = Tk()
Button(root, text='Set value to four',command=lambda *args: make_something(4)).pack()
Button(root, text='Set value to eight',command=lambda *args: make_something(8)).pack()
Button(root, text='Set value to fifteen',command=lambda *args: make_something(15)).pack()
#...etc

If each button modifies a different global, then condense all your globals into a single global dict, which make_something can then modify.

from tkinter import Tk, Button
settings = {"foo": 1, "bar": 1, "baz": 1}

def make_something(name):
    settings[name] = 2

root = Tk()
Button(root, text='Set foo',command=lambda *args: make_something("foo")).pack()
Button(root, text='Set bar',command=lambda *args: make_something("bar")).pack()
Button(root, text='Set baz',command=lambda *args: make_something("baz")).pack()
#...etc

In either case, you still only require one function.


If lambdas aren't to your taste, you could use nested functions to create separate callables for each command:

from tkinter import Tk, Button
settings = {"foo": 1, "bar": 1, "baz": 1}

def make_callback(key):
    def make_something(*args):
        settings[key] = 2
    return make_something

root = Tk()
Button(root, text='Set foo',command=make_callback("foo")).pack()
Button(root, text='Set bar',command=make_callback("bar")).pack()
Button(root, text='Set baz',command=make_callback("baz")).pack()
#...etc

... And you can avoid globals by instead using attributes of a class instance:

from tkinter import Tk, Button

class GUI:
    def __init__(self):
        self.settings = {"foo": 1, "bar": 1, "baz": 1}
        self.root = Tk()
        Button(self.root, text='Set foo',command=self.make_callback("foo")).pack()
        Button(self.root, text='Set bar',command=self.make_callback("bar")).pack()
        Button(self.root, text='Set baz',command=self.make_callback("baz")).pack()
        #...etc

    def make_callback(self, key):
        def make_something(*args):
            self.settings[key] = 2
        return make_something

gui = GUI()

By the way, don't do this:

myButton = Button(root).pack()

This assigns the result of pack() to myButton, so myButton will be None instead of referring to your button. Instead, do:

myButton = Button(root)
myButton.pack()
Answer from Kevin on Stack Overflow
Top answer
1 of 3
9

i need to make this for 6 buttons...

If each button modifies the same global variable, then have make_something accept a value parameter:

from tkinter import Tk, Button
variable = 1
def make_something(value):
    global variable
    variable = value
root = Tk()
Button(root, text='Set value to four',command=lambda *args: make_something(4)).pack()
Button(root, text='Set value to eight',command=lambda *args: make_something(8)).pack()
Button(root, text='Set value to fifteen',command=lambda *args: make_something(15)).pack()
#...etc

If each button modifies a different global, then condense all your globals into a single global dict, which make_something can then modify.

from tkinter import Tk, Button
settings = {"foo": 1, "bar": 1, "baz": 1}

def make_something(name):
    settings[name] = 2

root = Tk()
Button(root, text='Set foo',command=lambda *args: make_something("foo")).pack()
Button(root, text='Set bar',command=lambda *args: make_something("bar")).pack()
Button(root, text='Set baz',command=lambda *args: make_something("baz")).pack()
#...etc

In either case, you still only require one function.


If lambdas aren't to your taste, you could use nested functions to create separate callables for each command:

from tkinter import Tk, Button
settings = {"foo": 1, "bar": 1, "baz": 1}

def make_callback(key):
    def make_something(*args):
        settings[key] = 2
    return make_something

root = Tk()
Button(root, text='Set foo',command=make_callback("foo")).pack()
Button(root, text='Set bar',command=make_callback("bar")).pack()
Button(root, text='Set baz',command=make_callback("baz")).pack()
#...etc

... And you can avoid globals by instead using attributes of a class instance:

from tkinter import Tk, Button

class GUI:
    def __init__(self):
        self.settings = {"foo": 1, "bar": 1, "baz": 1}
        self.root = Tk()
        Button(self.root, text='Set foo',command=self.make_callback("foo")).pack()
        Button(self.root, text='Set bar',command=self.make_callback("bar")).pack()
        Button(self.root, text='Set baz',command=self.make_callback("baz")).pack()
        #...etc

    def make_callback(self, key):
        def make_something(*args):
            self.settings[key] = 2
        return make_something

gui = GUI()

By the way, don't do this:

myButton = Button(root).pack()

This assigns the result of pack() to myButton, so myButton will be None instead of referring to your button. Instead, do:

myButton = Button(root)
myButton.pack()
2 of 3
0

Update : I have it working (almost) fine This code works but I'd like to display in real time And when I uncoment the 2 things it doesn't do anything anymore

def BotPlay_Button():
    nPlay = entryN.get()
    jlist = [Joueur(File1,True,File1),Joueur(File2,True,File1)]
    Partie = Partie_Object(jlist)
    for i in range(int(nPlay)):
        Play_Partie(Partie)
        xList.append(i)
        y1List.append(bot1.score)
        y2List.append(bot2.score)
        # windo.update_idletasks()
        # windo.update()
๐ŸŒ
15. The Menu widget
anzeljg.github.io โ€บ rin2 โ€บ book2 โ€บ 2405 โ€บ docs โ€บ tkinter โ€บ control-variables.html
52. Control variables: the values behind the widgets
This is not necessary unless the ... label is static. ... Normally, you will set the widget's variable option to an IntVar, and that variable will be set to 1 when the checkbutton is turned on and to 0 when it is turned off....
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to change variables using entry with a button in tkinter? - Python Help - Discussions on Python.org
May 29, 2023 - I have set up a series of entries that change the colors of a canvas object in tkinter. While the print yielded results, it did not change the colors of said object in the canvas, making me wonder what did I do wrong in calling the Chara1 and/or ChangeVar functions. import tkinter as tk from ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to make a tkinter button change a variable
r/learnpython on Reddit: How to make a Tkinter Button change a variable
April 2, 2020 -

Is there a way to make a Tkinter Button change the value of a variable that I need somewhere else?

Here is my problem. I have a list of values, let us say "a[i]" with i=0...9.

I am listing the values, and then I want to ask the user for an entry to upgrade, and add 1 to that value. The user would enter the 'i', and then when clicking the button, the value of 'a[i]' would go up by 1. Here is my current code, that does not work. Any help would be greatly appreciated!

from tkinter import *

from tkinter import ttk

def upgradeByOne(iToUpgrade):

a[i] = a[i] + 1

# Define a list 'a' to start

a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

root = Tk()

mainwindow = ttk.Frame(root, width=200, height=200, padding="100 100 100 100")

mainwindow.grid(column=0, row=0, sticky=(N, W, E, S))

# Widgets for Main Window

ttk.Label(mainwindow, text="i").grid(column=0, row=0)

ttk.Label(mainwindow, text="a[i]").grid(column=1, row=0)

for i in range(0,10):

ttk.Label(mainwindow, text=i).grid(column=0, row=i+1)

ttk.Label(mainwindow, text=a[i]).grid(column=1, row=i+1)

ttk.Label(mainwindow, text="Which i would you like to upgrade?").grid(column=0, row=51, columnspan=3)

iToUpgrade = 0

whichIToUpgrade = ttk.Entry(mainwindow, width=7, textvariable=iToUpgrade)

whichIToUpgrade.grid(column=4, row=51, sticky=(W, E), columnspan=2)

ttk.Button(mainwindow, text="Upgrade",command= lambda: upgradeByOne(iToUpgrade)).grid(column=0,row=100,columnspan=5)

for child in mainwindow.winfo_children():

child.grid_configure(padx=5, pady=5)

# Main Loop

root.mainloop()

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ passing variables into tkinter button click event
r/learnpython on Reddit: Passing variables into Tkinter button click event
January 29, 2024 -

I'm close, but I think I'm missing something fundamental.

I'm programatically building some tkinter buttons and trying to get them to set a variable to some value (in this case, their own array index).

from tkinter import *
btnarray = [] array = []
def BtnClicked(obj, value): 
    obj = value
def CreateWindow():
    for idx in range(10):
        array.append(0)
        btnarray.append(Button(root, text = f"Button {idx}", command = lambda a = idx: BtnClicked( array[a] , a)))
        btnarray[-1].pack()
root = Tk()
CreateWindow()
while True:
    root.update()     

structure is representative of the application I inherited and am trying to alter. Why isn't it writing the values to array? if I break inside 'BtnClicked', obj gets the value written, but that somehow doesn't pass back to array.

Thanks!

๐ŸŒ
Plus2Net
plus2net.com โ€บ python โ€บ tkinter-button-dynamic.php
Dynamic button creation in Tkinter and handling events to pass data
February 5, 2019 - This list will be used to loop through and enable or disable each buttons by using the value of var ( the button which is clicked ) import tkinter as tk my_w = tk.Tk() my_w.geometry("300x200") # Size of the window my_w.title("www.plus2net.com") # Adding a title my_str = tk.StringVar() l1 = tk.Label(my_w, textvariable=my_str, width=10 ) l1.grid(row=0,column=2,columnspan=6) def show_lan(my_language,var): my_str.set(my_language) #loop through all the buttons to enable or disable each one for i in range(len(buttons)): if i==var: buttons[i].config(state="disabled") else: buttons[i].config(state="no
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Store button command into an variable - Python Help - Discussions on Python.org
November 3, 2022 - I would like to store the dynamically created text file name into a variable, to use with the button command. Is this possible? I have a test script, giving no error, but not workingโ€ฆ Any help will be appreciated โ€ฆ import tkinter as tk from tkinter import ttk # root window root = tk.Tk() ...
๐ŸŒ
YouTube
youtube.com โ€บ watch
An overview of the tkinter buttons (+using them with tkinter variables) - YouTube
This tutorial will cover how to use tkinter buttons (the basic button, the checkbutton and the radiobutton). Also, I will cover how you use tkinter variables...
Published ย  December 3, 2022
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/tkinter โ€บ reassigning global variables with button commands
r/Tkinter on Reddit: Reassigning Global Variables with Button Commands
January 16, 2024 -

Whenever I try to use one button to set a value of a Global Variable, the second button attempting to utilize or show the different variable does not work. can anyone explain what is going on and how I'm supposed to have different variables altered by different commands? I've also tried using intVar and it does not work either. Still resets to 0

var = 0

def changevar ():
    var = 1
    print(var)
def printvar():
    print(var)

window = tk.Tk()

button1 = tk.Button(master = window, text = "Set Var", command = changevar)
button1.pack()
button2 = tk.Button(master = window, text = "Display Var", command = printvar)
button2.pack()

window.mainloop()

Solved it. Had to use the "set" command for intvar so:

var = tk.IntVar()

def changevar ():
    var.set(1)
    print(var.get())
def printvar():
    print(var.get())

Top answer
1 of 2
1

Below code processes entry widget's text when Submit button is pressed.

import tkinter as tk

root = tk.Tk()

aVarOutside = 'asd'
def btn_cmd(obj):

    #use global variable
    global aVarOutside
    #print its unmodified value
    print("aVarOutside: " + aVarOutside)
    #modify it with what's written in Entry widget
    aVarOutside = obj.get()

    #modify lblTextVar, which is essentially modifying Label's text as lblTextVar is its textvariable
    lblTextVar.set(obj.get())

    #print what's inside Entry
    print("Entry: " + obj.get())

txt = tk.Entry(root)
txt.pack()

lblTextVar = tk.StringVar()
lbl = tk.Label(root, textvariable=lblTextVar)
lbl.pack()

btn = tk.Button(text="Submit", command=lambda obj = txt : btn_cmd(obj))
btn.pack()

root.mainloop()

When the button is pressed:

  1. Value of a global variable, aVarOutside is printed.
  2. Value of aVarOutside is modified to the value of Entry box's (txt's) content.
  3. Value of a textvariable used by a label (lbl) is modified. Which means that the text of lbl is updated and can be seen on the GUI.
  4. Finally Entry box, txt's content is printed.
2 of 2
0

I think you should use inputs() inside getInputs() and then button doesn't have to return any variables - and then you can use root.mainloop() instead of while loop.

import tkinter as tk

# --- functions ---

def inputs(text):
    # do something with text 
    print(text)

    # and return something      
    return 'a', 'b', 'c'

def get_input():
    global action_input, extra_input, texts

    text = textbox.get()

    if text: # check if text is not empty
        textbox.set('') # remove text from entry
        #textbox_entry.delete(0, 'end') # remove text from entry
        action_input, extra_input, texts = inputs(text)

# --- main ---

root = tk.Tk()

textbox = tk.StringVar()

textbox_entry = tk.Entry(root, textvariable=textbox)
textbox_entry.pack()

submit = tk.Button(root, text="Submit", command=get_input)
submit.pack()

root.mainloop()

BTW: you could better organize code

  • all functions before main part (root = tk.Tk())
  • PEP8 suggests to use lower_case_names for functions and variables (instead of CamelCaseNames)

global is not prefered method but I think it is better solution than yours.

If you don't need global then you can use classes with self.

import tkinter as tk

# --- classes ---

class Game:

    def __init__(self):
        self.root = tk.Tk()

        self.textbox = tk.StringVar()

        self.textbox_entry = tk.Entry(self.root, textvariable=self.textbox)
        self.textbox_entry.pack()

        self.submit = tk.Button(self.root, text="Submit", command=self.get_input)
        self.submit.pack()

    def run(self):
        self.root.mainloop()

    def inputs(self, text):
        # do something with text 
        print(text)

        # and return something      
        return 'a', 'b', 'c'

    def get_input(self):

        text = self.textbox.get()

        if text: # check if text is not empty
            self.textbox.set('') # remove text from entry
            #textbox_entry.delete(0, 'end') # remove text from entry
            self.action_input, self.extra_input, self.texts = self.inputs(text)

# --- functions ---

# empty


# --- main ---

app = Game()
app.run()
๐ŸŒ
Python Course
python-course.eu โ€บ tkinter โ€บ variable-classes-in-tkinter.php
4. Variable Classes in Tkinter | Tkinter | python-course.eu
December 16, 2021 - Some widgets (like text entry widgets, ... to will be updated to reflect the new value. These Tkinter control variables are used like regular Python variables to keep certain values....
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-24463.html
Returning a value from a tkinter.button call
I am trying to code without using globals. I am using the tkinter.button (see below) to enter some numbers into a variable. Ideally I want the tkinter.button call to return the number entered so that I don't have to make use of the global. Anyone a...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 75161272 โ€บ how-to-store-a-value-from-tkinter-button-on-a-var
python - How to store a value from Tkinter.Button on a var - Stack Overflow
Your button widgets can contain 'commands', my suggestion is, inside the function passed to the 'ask' command you can use tkinter's filedialog module, and use the output as needed. This is an example of using Stringvar, a tkinter dynamic variable, whenever you use the command set('') in it you will modify its value for the entire code, and to get the value you can use .get () anywhere in the code.
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ tkinter tutorial โ€บ tkinter stringvar
Tkinter StringVar - Python Tutorial
April 1, 2025 - The Tkinter StringVar helps you manage the value of a widget such as a Label or Entry more effectively. To create a new StringVar object, you use the StringVar constructor like this: string_var = tk.StringVar(master, value, name)Code language: ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-setting-and-retrieving-values-of-tkinter-variable
Setting and Retrieving values of Tkinter variable - Python - GeeksforGeeks
April 21, 2025 - The Radiobutton is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a Python function or method with each button.
๐ŸŒ
Beautiful Soup
tedboy.github.io โ€บ python_stdlib โ€บ generated โ€บ generated โ€บ Tkinter.Button.wait_variable.html
Tkinter.Button.wait_variable โ€” Python Standard Library
Tkinter.Button.wait_variable ยท View page source ยท Button.wait_variable(name='PY_VAR')ยถ ยท Wait until the variable is modified.
Top answer
1 of 1
1

There are several ways to accomplish your goal.

One way is to write a single function that will take a value to assign to your variable. This way you can have as many buttons as you like and only a single function.

Not if you are using functions you have to either pass the variable to the function or let the function know it is in the global namespace.

import tkinter as tk


root = tk.Tk()
selection = ''


def assign_value(value):
    global selection
    selection = value
    lbl["text"] = value
    print(selection)


lbl = tk.Label(root, text='Selection Goes Here')
lbl.grid(row=0, column=0)
tk.Button(text="General Knowledge", command=lambda: assign_value("General Knowledge")).grid(row=1, column=0)
tk.Button(text="Science", command=lambda: assign_value("Science")).grid(row=2, column=0)
tk.Button(text="Entertainment", command=lambda: assign_value("Entertainment")).grid(row=3, column=0)
tk.Button(text="Miscellaneous", command=lambda: assign_value("Miscellaneous")).grid(row=4, column=0)

root.mainloop()

Or you can assign the value directly from the button.

import tkinter as tk


root = tk.Tk()
selection = tk.StringVar()
selection.set('Selection Goes Here')


lbl = tk.Label(root, textvariable=selection)
lbl.grid(row=0, column=0)
tk.Button(text="General Knowledge", command=lambda: selection.set("General Knowledge")).grid(row=1, column=0)
tk.Button(text="Science", command=lambda: selection.set("Science")).grid(row=2, column=0)
tk.Button(text="Entertainment", command=lambda: selection.set("Entertainment")).grid(row=3, column=0)
tk.Button(text="Miscellaneous", command=lambda: selection.set("Miscellaneous")).grid(row=4, column=0)

root.mainloop()

I am sure if I spent more time on this I could think up something else but the idea is basically write your code in a more DRY (Don't Repeat Yourself) fashion and make sure you are assigning the value to the variable in the global namespace or else it will not work as you expect.

๐ŸŒ
TkDocs
tkdocs.com โ€บ pyref โ€บ variable.html
TkDocs - Variable
Class to define value holders for e.g. buttons. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations that constrain the type of the value returned from get(). Tkinter Class API Reference Contents ยท Class to define value holders for e.g.