473,813 Members | 3,448 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Two naive Tkinter questions

from Tkinter import *

class Application(Fra me):

def setcolor(self):
self["bg"] = "blue"

def createWidgets(s elf):
self.b1 = Button(self, bg = "red", command = self.setcolor)
self.b1.place(h eight = 50, width = 50)

self.b2 = Button(self, text = "Exit", command = self.quit)
self.b2.place(h eight = 50, width = 50, x = 50)

def __init__(self, master=None):
Frame.__init__( self, master)
self.place(heig ht = 50, width = 100)
self.createWidg ets()

app = Application()
app.mainloop()
1) When I run this program, it displays two buttons. When I click the
button on the left, I would like the color of that button to change from red
to blue. This code is obviously the wrong way to accomplish this, because
when setcolor is called, it gets the button's parent, not the button itself.
How do I arrange for setcolor to get the right object?

2) The window in which these buttons appear is the wrong size, and does not
depend on the height and width given to self.place in __init__. Yet the
height and width arguments do something, because if I set width to 75, it
cuts off half the right-hand button. How do I say how large I want the
window to be?
Jul 18 '05 #1
5 1962
"Andrew Koenig" <ar*@acm.org> writes:
1) When I run this program, it displays two buttons. When I click the
button on the left, I would like the color of that button to change from red
to blue. This code is obviously the wrong way to accomplish this, because
when setcolor is called, it gets the button's parent, not the button itself.
How do I arrange for setcolor to get the right object?
In the specific example, you could just *know* that setcolor deals
with self.b1. In the more general example, you can create dynamic
callback functions:

self.b1 = Button(self, bg = "red",
command = lambda: self.b1.config( bg="blue"))

This uses a number of tricks: the lambda function has no arguments,
yet it uses self - so it is a nested function. Also, inside a lambda
function, you can have only expressions, so self.b1['bg']='blue' would
not be allowed. In the general case, and not assuming nested
functions, you would write

def createWidgets(s elf):
def b1_setcolor(sel f=self):
self.b1['bg']='blue'
self.b1 = Button(self, bg = "red", command=b1_setc olor)
2) The window in which these buttons appear is the wrong size, and does not
depend on the height and width given to self.place in __init__. Yet the
height and width arguments do something, because if I set width to 75, it
cuts off half the right-hand button. How do I say how large I want the
window to be?


The problem is that there is another toplevel widget around your
frame; the frame itself has the size you have specified. You could
either use Toplevel instead of Frame as a base, or you could adjust
the size of the root window, e.g. through

app.master.wm_g eometry("100x50 ")

HTH,
Martin

Jul 18 '05 #2
> In the specific example, you could just *know* that setcolor deals
with self.b1. In the more general example, you can create dynamic
callback functions:

self.b1 = Button(self, bg = "red",
command = lambda: self.b1.config( bg="blue"))

This uses a number of tricks: the lambda function has no arguments,
yet it uses self - so it is a nested function. Also, inside a lambda
function, you can have only expressions, so self.b1['bg']='blue' would
not be allowed. In the general case, and not assuming nested
functions, you would write

def createWidgets(s elf):
def b1_setcolor(sel f=self):
self.b1['bg']='blue'
self.b1 = Button(self, bg = "red", command=b1_setc olor)
I worked out something similar, but I must confess that it appears
needlessly complicated. I was hoping for a simpler solution, such as a
variation of the "command" attribute that would cause its associated
argument to be called with the button rather than its parent.

Your first suggestion, knowing that setcolor deals with self.b1, doesn't
work with my application because I'm going to have lots of these buttons,
and I want to be able to set their colors independently.
2) The window in which these buttons appear is the wrong size, and does not depend on the height and width given to self.place in __init__. Yet the
height and width arguments do something, because if I set width to 75, it cuts off half the right-hand button. How do I say how large I want the
window to be?


The problem is that there is another toplevel widget around your
frame; the frame itself has the size you have specified. You could
either use Toplevel instead of Frame as a base, or you could adjust
the size of the root window, e.g. through

app.master.wm_g eometry("100x50 ")


Gotcha -- thanks.
Jul 18 '05 #3
Andrew Koenig wrote:
work with my application because I'm going to have lots of these buttons,
and I want to be able to set their colors independently.


If you have many buttons with similar functionality, I'd suggest using a
subclass, e. g.:

import Tkinter as tk

class ColorButton(tk. Button):
def __init__(self, master, text, color):
tk.Button.__ini t__(self, master, text=text, command=self.ex ecute)
self.color = color
def execute(self):
self["background "] = self.color
root = tk.Tk()
for color in "red green blue yellow".split() :
ColorButton(roo t, text=color.capi talize(), color=color).pa ck()
root.mainloop()

Peter
Jul 18 '05 #4
On Sun, 02 Nov 2003 21:32:12 GMT, "Andrew Koenig" <ar*@acm.org>
wrote:
Your first suggestion, knowing that setcolor deals with self.b1, doesn't
work with my application because I'm going to have lots of these buttons,
and I want to be able to set their colors independently.


A slight variant on the technique using lambda is:

def setcolor(self,w idget=self):
widget['bg']='blue'
def createWidgets(s elf):
self.b1 = Button(self, bg = "red",
command=lambda: self.setcolor(s elf.b1))

Here we use the lambda to call the setcolor method with
the widget parameter and use that within the setcolor method.

This way you keep one method but call it from several places.
The downside is you introduce an extra function call, but in
a GUI event handler that's not going to be a problem!

HTH,

Alan G.


Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld
Jul 18 '05 #5
On Sun, 2003-11-02 at 21:32, Andrew Koenig wrote:
In the specific example, you could just *know* that setcolor deals
with self.b1. In the more general example, you can create dynamic
callback functions:

self.b1 = Button(self, bg = "red",
command = lambda: self.b1.config( bg="blue"))

This uses a number of tricks: the lambda function has no arguments,
yet it uses self - so it is a nested function. Also, inside a lambda
function, you can have only expressions, so self.b1['bg']='blue' would
not be allowed. In the general case, and not assuming nested
functions, you would write

def createWidgets(s elf):
def b1_setcolor(sel f=self):
self.b1['bg']='blue'
self.b1 = Button(self, bg = "red", command=b1_setc olor)


I worked out something similar, but I must confess that it appears
needlessly complicated. I was hoping for a simpler solution, such as a
variation of the "command" attribute that would cause its associated
argument to be called with the button rather than its parent.

Your first suggestion, knowing that setcolor deals with self.b1, doesn't
work with my application because I'm going to have lots of these buttons,
and I want to be able to set their colors independently.

For this I would use a callback class and it's __call__ method

(untested)

class Callback:
def __init__(self, button, colour):
self.button = button
self.colour = colour
def __call__(self):
self.button.con fig(background = self.colour)

self.b1 = Button(self, background = "red")
self.b1.config( command = Callback(self.b 1, "blue"))
self.b1.pack(.. ...)

Regards
Martin
--
Martin Franklin <mf********@gat wick.westerngec o.slb.com>
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
4893
by: Mark 'Kamikaze' Hughes | last post by:
In the new Python game I'm developing, I need to crop out individual tiles from larger tilesets, and maintain transparency. Unfortunately, I've run into major deficiencies in both Tkinter and PIL (PyGame, wxPython, PyQt, etc. are not really suitable for this program, for a number of reasons, and I have zero interest in discussing why right now). Since the Tkinter.PhotoImage.copy() method doesn't allow a region parameter, I have to save...
3
2349
by: Mickel Grönroos | last post by:
Hi everybody, I'm using QuickTimeTcl (3.1) to be able to play movie files in my Tkinter application (Python 2.3.2) on Windows 2000. I was planning to write a simple wrapper class, QuickTimeMovie, that would wrap up the QuickTimeTcl Tcl extension as a Python class. All seems to work pretty fine until the Tkinter application is closed, when the Python interpreter crashes with an error of the following kind: The instruction at...
2
2503
by: import newbie | last post by:
Hi all, I'm a programming dabbler trying learn Python, and I've got a few questions. Mainly: Where can I find a good open-source library or tutorial (preferably free) that explains how to easily manipulate text in a tKinter window? Basically, I want to be able to do anything that HTML can do (or close to it) but without the HTML. :-)
1
2237
by: John Chambers | last post by:
Sp my latest adventure is attempting to use python's Tkinter module on a few machines. On my PB (OSX 10.3.9), I got the following confusing results: /Users/jc: python Python 2.3 (#1, Sep 13 2003, 00:49:11) on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter Traceback (most recent call last): File "<stdin>", line 1, in ?
3
1246
by: Franz Steinhaeusler | last post by:
Hello NG, I'm asking this, (although I know a mailing list on gmane gmane.comp.python.tkinter and there is so little traffic compared to the mailing list of wxPython also mirrored on gmane gmane.comp.python.wxpython. I cannot imagine, that there is no more interest in exchanging opinions, or is this really the case?
3
4892
by: pragy | last post by:
Hey, can any one help me for writing a program of naive gauss elimintaion technique? It's a technique to solve system of simultaneous linear equations using matrix. thanks
7
1666
by: Dick Moores | last post by:
In a couple of places recently I've seen Brent Welch's _Practical Programming in Tcl & Tk_ (<http://tinyurl.com/ynlk8b>) recommended for learning Tkinter well. So a couple of questions: 1) Is it really good for learning Tkinter, even though it doesn't mention Tkinter at all (in the 4th edition at least)? 2) If it is good for learning Tkinter, can I get by with a cheaper,
4
2002
by: fabdeb | last post by:
Hi every one, I m a sysadmin who want to know how to use python. I dont know anything about oriented object programation, i only know bash and a little perl. I have some simple questions about python. the first: what is the differences between a function and a classe? In which case i should use a function ? In which case i should use a class ?
4
2887
by: Davy | last post by:
Hi all, I have written a simple Tkinter program, that is draw a rectangle in a canvas, when I press Up key, the rectangle move up. But the program seems work not properly? My environment is Python2.5+PythonWin. ##---------------------- from Tkinter import * class MyApp:
0
9734
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10665
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10420
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6897
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5568
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5704
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4358
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3881
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3029
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.