Home > Software engineering >  Trying to get Tkinter button to add brackets on either side of button text with every press
Trying to get Tkinter button to add brackets on either side of button text with every press

Time:09-27

I'm trying to create a button which has the same effect as the button from the version test from tkinter when using the command

py -m tkinter

in CMD. The button is supposed to display the text "Button", then with every press a set of brackets will be added on either side of the word. So on the first press, the text will read "[Button]", then the second press "[[Button]]", and so on.

Here is what I have:

from tkinter import *
from tkinter import ttk

def changeText():
    textName = "["   textName   "]"

root = Tk()
root.geometry('400x150')
root.title('Hit the button')

textName = "button"
frame = ttk.Frame(root, padding = 10).grid()
btn = ttk.Button(frame, text = textName, command = changeText).grid(column = 0, row = 0)
root.mainloop()

When I run my code, the window and button pops up correctly, however when the button is pressed, I get the error:

"X:\Pycharm Environments\venv\Scripts\python.exe" "X:/Pycharm Environments/Learning/tkinterPractie.py" 
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\jared\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1885, in __call__
    return self.func(*args)
  File "X:\Pycharm Environments\Learning\tkinterPractie.py", line 5, in changeText
    textName = "["   textName   "]"
UnboundLocalError: local variable 'textName' referenced before assignment

I'm not really sure what I'm doing wrong here. Thanks for any help!

CodePudding user response:

When you call .grid() on your button, the return value is None, so you have already lost the direct reference to your button. There are other ways of accessing it, but it would be much easier to just create the button and then put it in the layout in 2 steps. Also you need to set the button['text'] when changing the text. textName is just a variable holding a string and updating it only updates the value of the variable.

from tkinter import *
from tkinter import ttk

def changeText():
    btn['text'] = "["   btn['text']   "]"  # change to changing the buttons text

root = Tk()
root.geometry('400x150')
root.title('Hit the button')

textName = "button"
frame = ttk.Frame(root, padding = 10).grid()
btn = ttk.Button(frame, text = textName, command = changeText)  # return the instance
btn.grid(column = 0, row = 0)  # then input into the layout
root.mainloop()
  • Related