So i decided to do this for a school project and am completely new to tkinter (but not new to python). But in the parts where the "cookie" values should be printed - they dont get printed.
I dont know how to properly paste code here so here's github: https://gist.github.com/avaque/a5fd47b896c8ff4e9e52d206994187ce
It looks like a mess, but thats not what matters (i think). The problem is that it doesn't print integers defined as "a" representing the cookie amount.
I started from this code: https://www.python-course.eu/tkinter_buttons.php ...and in that one the string gets printed. Is the value type a problem here?
And also is it possible for the cookie amount to be displayed in a button's text? (look at row 70-74)pythontkinter
The problem is that it doesn't print integers defined as "a" representing the cookie amount.
If I understand correctly, your
buttonzy is supposed to print the amount when clicked, and it doing just that. The main problem is that you're not updating your
a variable correctly.
slogan = tk.Button(frame, text="Cookie click!", command=clicc(a,b))
First thing: you can't directly send arguments to functions used as commands to your tkinter buttons. One approach is to use a lambda operator. So you could rewrite the line above (and all the other ones that try to send arguments to the command functions) as follows:
slogan = tk.Button(frame, text="Cookie click!", command=lambda: clicc(a,b))
Just a reminder that if you don't need to send any arguments, there's no need to use lambda.
The second problem you are having is with the
clicc() function. When you call it from the
slogan button, you're sending the
b variables, and, supposedly updating the value from
a. What actually happens is that, when you send the values from
b to the function, these values are allocated to local variables, that shadow the names from your global variables. So any alteration that you might do inside the function, as
a=a+b, will only change the value from you local variables, and leave your global variables unaltered. The same happens in the
You can read more about the local/global variables dynamics here.
The most direct solution to you problem, although far from the most elegant, is to add the
global keyword with the variable names at the start of the functions that do try to modify the values from global variables. For example, your clicc() function could look like:
def clicc(x, y): global a a=x+y
Notice how I changed the first argument from
x, so as to not use the same variable names.
Another solution would be to work with other types of objects, like lists or even classes, to avoid the need of global variables, so you might want to look into that.
And also is it possible for the cookie amount to be displayed in a button's text?
In the link you've provided, they show an example with a label, but it is exactly the same with buttons. You can do something like
buttonzy.config(text=str(a)) after updating the value from