0

In the code below, which I made more simple for this purpose, I first create a function and then make a button, which is supposed to call that function. I got really stuck here because I want to use the changed variable later in my code but it doesn't change, which I understand, since I don't return it but have no idea, how to save it when it's called this way.

import tkinter as tk

root = tk.Tk()
x = 1
def do_something(x):
    x += 1

button = tk.Button(root, command=lambda: do_something(x))
root.mainloop()

Firstly, I don't understand, why I have to put there the x argument, even though it is defined before the function is created (in my code it says, that it is not defined), and secondly, I don't know how to save the x for later use. In my code, the function does more than just this, so I can't simply put it in lambda function. I appreciate any help, if I was unclear, please, let me know, I'll try to explain better. Thank you Now I realized, that probably just because x is not defined in that function, the value does not change globally. But still have no idea why its not defined there...

Tarke
  • 1
  • 1
  • check https://stackoverflow.com/questions/423379/using-global-variables-in-a-function for how to use global variables. – Wups Feb 03 '22 at 20:39

1 Answers1

-1

The code can be written in two ways:

import tkinter as tk

root = tk.Tk()
x = 1
def do_something():
    global x
    x+=1
    return print(x)

button = tk.Button(root, command=do_something)
button.pack()
root.mainloop()

Or

import tkinter as tk

root = tk.Tk()
x = 1

button = tk.Button(root, command=lambda x: x+=1)
root.mainloop()
Rahul Das
  • 11
  • 2