On 01/07/18 02:17, Alan Gauld via Tutor wrote:
On 30/06/18 03:55, Chris Roy-Smith wrote:

I am trying to change the command of a tkinter Button in my program.
Eventually I want to be able to do this to many buttons.
Since I'm not 100% sure if you mean the command or the label or both
here is a simple example that does both...

############################################
import tkinter as tk

def cmd1(): print('This is command 1')

def cmd2(): print('This is number 2')
I was hoping eventually to generate the command form the results of a database query, not knowing  the exact command until run time. Perhaps what I was trying to achieve is too close to self modifying code, I was warned off this when I used to dabble in assembler. Does the same advice hold for python?

def swapCmd():
     c = b1['command']
     # kluge to get the function name from Tcl id
     if str(c).endswith("cmd1"):
         b1['command'] = cmd2
     else:
         b1['command'] = cmd1
I never thought to try anything like this, I was thinking more along the lines for how to change the text of a Labe.l
def swapText():
     t = b1['text']
     if t == "Cool":
         b1['text'] = "Hot"
     else:
         b1['text'] = "Cool"

# make GUI
top = tk.Tk()
win = tk.Frame(top)
win.pack()
b1 = tk.Button(win,text="Cool", command=cmd1)
b1.pack()
b2 = tk.Button(win, text="Swap text", command=swapText)
b2.pack()
b3 = tk.Button(win, text="Swap cmd", command=swapCmd)
b3.pack()

top.mainloop()
###########################################

Thank you again Alan,
While your solution works, it's not how I imagined in terms of approach. Eventually I wanted to change the command of a variable number of buttons with the actual command depending on the results of a database query. I am unable to see how I can manage this in your solution style ( predetermined commands) might be difficult to achieve ( with my limited programming skills ).  Your solution made me rethink what I was attempting to do, and found with a slightly modified database query, I didn't need to change the command at all. The rest of this bit of program I have already solved.
Now I just have to learn a lot more about classes, and objects.

again, thank you Alan.
Regards, Chris Roy-Smith
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to