954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

GUI Button switching

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()

effBlam
Newbie Poster
13 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

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()
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

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

effBlam
Newbie Poster
13 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: