I'm confused on how i can change or "toggle" the text of a button from say "D" to "A" when clicked, and then back to "D" if clicked again. So far I have this:

from Tkinter import *
from tkFileDialog import *

class Game(Frame):
	def __init__(self,root):
		Frame.__init__(self,root)
		self.grid()
		self.buttons()
	
	def buttons(self):
		for x in range(10):
			for y in range(10):
				self.liveButton = Button (self, text="D", width=5)
				self.liveButton.grid(row=x,column=y)	

def main():
	root = Tk()
	root.title("Sample Application")
	root.geometry("150x150")
	Game(root)
	root.mainloop()
main()

One way is to use a StringVar. When you change it's contents, the change shows up on the GUI. And you should read up on buttons as yours don't do anything when clicked.

from Tkinter import *
from tkFileDialog import *

class Game():
    def __init__(self,root):
        self.root = root
        self.var1 = StringVar()
        self.var1.set("D")
        btn = Button (self.root, textvariable=self.var1, width=5, command=self.change_var)
        btn.grid(row=1,column=1)	

    def change_var(self):
        var=self.var1.get()
        if "A"==var:
            self.var1.set("D")
        else:
            self.var1.set("A")

root = Tk()
root.title("Sample Application")
root.geometry("100x50")
Game(root)
root.mainloop()

Edited 5 Years Ago by woooee: n/a

Sweet thanks, I should've binded the button before putting up code, it was really that if statement that was getting to me

This article has been dead for over six months. Start a new discussion instead.