[Tutor] how to change the command "string" on a tkinter Button?

Alan Gauld alan.gauld at yahoo.co.uk
Sun Jul 1 15:07:17 EDT 2018


On 01/07/18 09:15, Chris Roy-Smith wrote:

>> 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?

writing sel;f modifying code is so difficult to get right and
so easy to be catastrophically wrong that its best avoided
in any language. Even guru level programmers get that stuff
wrong.

But it sounds like you probably want data driven code which
is (still tricky but) a lot easier. Tell us more with some
examples of the data and we can probably help.

> 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. 

Sure, but the actual changing of the command will
still look like my code I suspect.

The tricky bit is creating the appropriate function
object so that you can assign it,.

The number of widgets is just a matter of a list
and an iterator....

And remember, in a GUI everyting is event driven so you need to think
about what event will trigger this reassignment of commands.

You need the GUI in place and some kind of event catcher
(button?, timer?) to handle the changeover.

> 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.

OK, Glad you avoided the tricky stiff. Its very rarely needed.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list