1

i want to make a Button that changes the displayed text(number) after every click and returns the valure defined in the function, because i want to work with the displayed variables.

I created a function that adds +1 to "text" after every click until 4 and a button. The code does not return the valure of the function and the button has only the text = 1,2,3 or 4.

import tkinter as tk

root = tk.Tk()

text = 0
def text_change():
    global text
    text += 1

    print(text)
    if text >= 4:
        text = 0

#to change: button text has to be the variable defined in the function
btn = tk.Button(text = "1,2,3 or 4", width = 10, height = 3, command = \
                text_change).grid(row = 1 , column = 1)

root.mainloop()

I hope you can help me :)

2
  • 1
    Clicked Button can't return value. Commented Nov 26, 2015 at 13:41
  • btw: btn = tk.Button(...).grid(..) always assigns None to btn. Use use btn = tk.Button(...) ; btn.grid(...) Commented Nov 26, 2015 at 13:45

1 Answer 1

1

First

btn = tk.Button(...).grid(..)

assigns None to btn because grid() returns None

use

btn = tk.Button(...)
btn.grid(...)

Now you can change text on button using btn['text'] = "new text" or btn.config(text="new text")

import tkinter as tk

# --- functions ---

def text_change():
    global text

    text += 1

    if text > 4:
        text = 1

    print("changed to:", text)

    #btn['text'] = text
    btn.config(text=text)

def text_print():
    print("current:", text)

# --- main ---

text = 0

root = tk.Tk()

btn = tk.Button(text="1,2,3 or 4", command=text_change, width=10, height=3)
btn.grid(row=1, column=1)

btn2 = tk.Button(text="SHOW", command=text_print, width=10, height=3)
btn2.grid(row=2, column=1)

root.mainloop()
Sign up to request clarification or add additional context in comments.

8 Comments

thank you! Do you know how to assigne the 1,2,3 or 4 to a variable ? So i can work with the variables
I don't know what you mean. You already have text variable and you can work with it.
yea but i think the text value in "text_change()" is local, so the text = 0 ist always 0. And i want to overwrite the text = 0 with the text-value of "text_change()"
as an example my code : a = text if a == 1: print("kkk") doesnt work
text is not local because I used global text
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.