9

Im trying to make it so that when the user clicks a button, it becomes "X" or "0" (Depending on their team). How can I make it so that the text on the button is updated? My best idea so far has been to delete the buttons then print them again, but that only deletes one button. Here's what I have so far:

from tkinter import *

BoardValue = ["-","-","-","-","-","-","-","-","-"]

window = Tk()
window.title("Noughts And Crosses")
window.geometry("10x200")

v = StringVar()
Label(window, textvariable=v,pady=10).pack()
v.set("Noughts And Crosses")

def DrawBoard():
    for i, b in enumerate(BoardValue):
        global btn
        if i%3 == 0:
            row_frame = Frame(window)
            row_frame.pack(side="top")
        btn = Button(row_frame, text=b, relief=GROOVE, width=2, command = lambda: PlayMove())
        btn.pack(side="left")

def PlayMove():
    BoardValue[0] = "X"
    btn.destroy()
    DrawBoard()

DrawBoard()
window.mainloop()
ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46
Mrchooch
  • 171
  • 1
  • 1
  • 9

7 Answers7

31

To sum up this thread: button.config and button.configure both work fine!

button.config(text="hello")

or

button.configure(text="hello")
ymdred16
  • 98
  • 3
  • 15
Trieu Nguyen
  • 933
  • 1
  • 11
  • 17
15

The Button widget, just like your Label, also has a textvariable= option. You can use StringVar.set() to update the Button. Minimal example:

import tkinter as tk

root = tk.Tk()

def update_btn_text():
    btn_text.set("b")

btn_text = tk.StringVar()
btn = tk.Button(root, textvariable=btn_text, command=update_btn_text)
btn_text.set("a")

btn.pack()

root.mainloop()
David
  • 624
  • 6
  • 15
  • 1
    How can I make it so that the button clicked is the one that changes, though. Right now it just updates the last button for some reason – Mrchooch Sep 16 '15 at 19:15
  • 1
    @Mrchooch You need a seperate `tk.StringVar ` for every Button. Look at http://effbot.org/tkinterbook/variable.htm – David Sep 16 '15 at 19:46
  • 2
    You can also just call the `configure` method of the button, without having to use a `StringVar`. While using `StringVar` will work, it's adding an extra object to maintain without giving any added benefit. – Bryan Oakley Sep 26 '15 at 22:27
5

btn is just a dictionary of values, lets see what comes up then:

#lets do another button example
Search_button
<tkinter.Button object .!button>
#hmm, lets do dict(Search_button)
dict(Search_button)
{'activebackground': 'SystemButtonFace', 'activeforeground': 
'SystemButtonText', 'anchor': 'center', 'background': 'SystemButtonFace', 
'bd': <pixel object: '2'>, 'bg': 'SystemButtonFace', 'bitmap': '', 
'borderwidth': <pixel object: '2'>, 'command': '100260920point', 'compound': 
'none', 'cursor': '', 'default': 'disabled', 'disabledforeground': 
'SystemDisabledText', 'fg': 'SystemButtonText', 'font': 'TkDefaultFont', 
'foreground': 'SystemButtonText', 'height': 0, 'highlightbackground': 
'SystemButtonFace', 'highlightcolor': 'SystemWindowFrame', 
'highlightthickness': <pixel object: '1'>, 'image': '', 'justify': 'center', 
'overrelief': '', 'padx': <pixel object: '1'>, 'pady': <pixel object: '1'>, 
'relief': 'raised', 'repeatdelay': 0, 'repeatinterval': 0, 'state': 
'normal', 'takefocus': '', 'text': 'Click me for 10 points!', 
'textvariable': '', 'underline': -1, 'width': 125, 'wraplength': <pixel 
object: '0'>}
#this will not work if you have closed the tkinter window

As you can see, it is a large dictionary of values, so if you want to change any button, simply do:

Button_that_needs_to_be_changed["text"] = "new text here"

Thats it really!

It will automatically change the text on the button, even if you are on IDLE!

3

use myButtonObject["text"] = "Hello World"

python 3

from tkinter import *

btnMyButton = Button(text="Im Button", command=onClick)
btnMyButton["text"] = "Im not button"

python 2

import Tkinter as tk

btnMyButton = tk.Button(text="Im Button", command=onClick)
btnMyButton["text"] = "Im not button"
mesutpiskin
  • 1,771
  • 2
  • 26
  • 30
2

Another way is by btn.configure(text="new text"), like this:

import tkinter as tk
root = tk.Tk()

def update_btn_text():
    if(btn["text"]=="a"):
        btn.configure(text="b")
    else:
        btn.configure(text="a")


btn = tk.Button(root, text="a", command=update_btn_text)
btn.pack()

root.mainloop()
ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46
1

I think that code will be useful for you.

import tkinter 
from tkinter import *
#These Necessary Libraries

App = Tk()
App.geometry("256x192")

def Change():
    Btn1.configure(text=Text.get()) # Changes Text As Entry Message.
    Ent1.delete(first=0, last=999) # Not necessary. For clearing Entry.

Btn1 = Button(App, text="Change Text", width=16, command=Change)
Btn1.pack()

Text = tkinter.StringVar() # For Pickup Text

Ent1 = Entry(App, width=32, bd=3, textvariable=Text) #<-
Ent1.pack()

App.mainloop()
ForceVII
  • 355
  • 2
  • 16
-1
from tkinter import *

BoardValue = ["-","-","-","-","-","-","-","-","-"]

window = Tk()
window.title("Noughts And Crosses")
window.geometry("10x200")

v = StringVar()
Label(window, textvariable=v,pady=10).pack()
v.set("Noughts And Crosses")

btn=[]

class BoardButton():
    def __init__(self,row_frame,b):
        global btn
        self.position= len(btn)
        btn.append(Button(row_frame, text=b, relief=GROOVE, width=2,command=lambda: self.callPlayMove()))
        btn[self.position].pack(side="left")

    def callPlayMove(self):
        PlayMove(self.position)

def DrawBoard():
    for i, b in enumerate(BoardValue):
        global btn
        if i%3 == 0:
            row_frame = Frame(window)
            row_frame.pack(side="top")
        BoardButton(row_frame,b)
        #btn.append(Button(row_frame, text=b, relief=GROOVE, width=2))
        #btn[i].pack(side="left")

def UpdateBoard():
    for i, b in enumerate(BoardValue):
        global btn
        btn[i].config(text=b)

def PlayMove(positionClicked):
    if BoardValue[positionClicked] == '-':
        BoardValue[positionClicked] = "X"
    else:
        BoardValue[positionClicked] = '-'
    UpdateBoard()

DrawBoard()
window.mainloop()
  • The asymmetry between setting a widget's text and getting its text is frustrating. The latter requires "text" in quotes, the former does not. – Jonathan Allin Sep 20 '21 at 09:57