Search code examples
pythonuser-interfacebuttontkinterttk

Button Label - text vs textvariable


TTK Button: text vs textvariable I am trying to set the button label text to "Hi" as a default and, on clicking it, change its text to "Hello"

I have tried multiple methods to get the text to change.

If I set the text = "Hi" it's fine, but whenever I add in the textvariable, it breaks and displays no text label on the button, itself.

Is there something wrong with adding both the text and textvariable arguments when constructing the button in tkinter, as below?

From Python GUI Programming with Tkinter by Alan D. Moore

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

tvar = tk.StringVar()
def swaptext():
    if tvar.get() == 'Hi':
        tvar.set('There')
    else:
        tvar.set('Hi')

# my_button = ttk.Button(parent, text='Hi', textvariable=tvar, command=swaptext) # BUTTON LABEL IS BLANK
my_button = ttk.Button(parent, text='Hi', command=swaptext) # WORKS, BUT NO TEXTVARIABLE TO CALL TO SWAP TEXT
my_button.pack()

root.mainloop()

I expect the button to show, immediately, with "Hi" given the default text value is set to "Hi", but it actually starts out BLANK. Though it starts blank, when I click the button, it toggles from:

  • BLANK --> Hi

  • Hi --> Hello

  • Hello --> Hi (etc. etc.)

Can anyone point out to me what I am doing wrong as to why my default button text value and the textvariable?

The closest I found to an answer was here: TextVariable not working, but this was in regards to Entry constructors, which don't appear to take text as an argument.

If I missed an answer to this, I apologize, but I'm not seeing one listed anywhere.


Solution

  • You didn't set a default value for your StringVar.

    import tkinter as tk
    from tkinter import ttk
    
    root = tk.Tk()
    
    tvar = tk.StringVar(value="Hi")
    
    def swaptext():
        if tvar.get() == 'Hi':
            tvar.set('There')
        else:
            tvar.set('Hi')
    
    my_button = ttk.Button(root, textvariable=tvar, command=swaptext)
    my_button.pack()
    
    root.mainloop()