473,657 Members | 2,515 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with tkinter

hello.

the following code:

1 from Tkinter import *
2
3 class MiaApp:
4 def __init__(self, genitore):
5 self.mioGenitor e = genitore
6 self.i = IntVar()
7 self.i.set(42)
8 self.s = StringVar()
9 self.s.set("Bao bab")
10 self.lab = {}
11 self.lab["self.i"] = Label(self.mioG enitore)
12 self.lab["self.i"].configure(widt h = 30, relief = RIDGE,
13 text = "[vuota]")
14 self.lab["self.i"].pack()
15 self.lab["self.s"] = Label(self.mioG enitore)
16 self.lab["self.s"].configure(widt h = 30, relief = RIDGE,
17 text = "[vuota]")
18 self.lab["self.s"].pack()
19 self.but = Button(self.mio Genitore)
20 self.but.config ure(text = "Vai!", command = self.procedi)
21 self.but.pack()
22 def procedi(self):
23 for var in ("self.i", "self.s"):
24 self.lab[var].configure(text variable = var)
25
26 radice = Tk()
27 miaApp = MiaApp(radice)
28 radice.mainloop ()

is intended to make a window with 2 labels and a button, such that
pressin the button you get the labels display the content of two
variables. it does not work, of course, as intended. is there anybody
who can point me in the right direction? (the problem seems to be that
the command option wants a variable name, not a string containing that
name).

hopefully

macs
Jul 18 '05 #1
5 2050
Instead of indexing self.lab by strings, you can index them by the
attributes themselves : self.lab[self.i], and change line 23 into

for var in (self.s, self,i)

For your example, I wouldn't have used the "text" option in the
definition of the labels, then "textvariab le" in the callback method
(procedi) ; I would have used only "text" and no IntVar or StringVar,
just an integer and a string :

class MiaApp:
def __init__(self, genitore):
self.mioGenitor e = genitore
self.i = 42
self.s = "Baobab"
self.lab = {}
self.lab[self.i] = Label(self.mioG enitore)
self.lab[self.i].configure(widt h = 30, relief = RIDGE,
text = "[vuota]")
self.lab[self.i].pack()
self.lab[self.s] = Label(self.mioG enitore)
self.lab[self.s].configure(widt h = 30, relief = RIDGE,
text = "[vuota]")
self.lab[self.s].pack()
self.but = Button(self.mio Genitore)
self.but.config ure(text = "Vai!", command = self.procedi)
self.but.pack()
def procedi(self):
for var in (self.i, self.s):
self.lab[var].configure(text = var)

Regards,
Pierre
Jul 18 '05 #2
On Tue, 29 Mar 2005 22:32:59 +0200, Pierre Quentel <qu************ @wanadoo.fr> wrote:
Instead of indexing self.lab by strings, you can index them by the
attributes themselves : self.lab[self.i], and change line 23 into

for var in (self.s, self,i)
I really think this is asking for trouble: I suppose that the i and s attributes are meant to change at some point in the future, and you're mapping their *values* to the corresponding labels. So if the value changes, you won't be able to get the label again.
For your example, I wouldn't have used the "text" option in the
definition of the labels, then "textvariab le" in the callback method
(procedi) ; I would have used only "text" and no IntVar or StringVar,
just an integer and a string :


I would have done exactly the contrary, as it is far more easier to use. Using the textvariable option in Label's does not require you to remember the labels, but only the variables used to hold their contents. I'd also use two mappings: the first mapping a name to a Tkinter variable for the label variables, and the second for the values to give to these variables later.

Here is my version of the class code:

class MiaApp:
def __init__(self, genitore):
self.mioGenitor e = genitore
## Mapping for variables
self.variables = {
"i" : StringVar(),
"s" : StringVar()
}
## Mapping for future variable values
self.values = {
"i" : 42,
"s" : "Baobab"
}
## Now, create the labels
for var in self.variables. values():
## Default text
var.set("[vuota]")
## Create label
lb = Label(self.mioG enitore, width=30, relief=RIDGE, textvariable=va r)
lb.pack()
## The button is no more remembered in an attribute, as it does not seem to be needed
but = Button(self.mio Genitore, text = "Vai!", command = self.procedi)
but.pack()

def procedi(self):
## Just change the variable values
for varName in self.variables. keys():
self.variables[varName].set(self.value s[varName])

Note that I only used StringVar's: since the variable holds the *text* for a Label, it is not a good idea to use anything else. I tend to use IntVar, BooleanVar or DoubleVar only when I'm sure it won't ever be set to anything else than an integer, a boolean or a float respectively. So for Label and Entry text variables, I always use a StringVar. In spite of their name, these variable can actually hold anything; you will just get the value you've given to them as text rather than as their original type:
v = StringVar()
v.set(42)
v.get()

'42'

So if you want to get the integer back, you'll need to convert the value explicitely. This is in fact what is done by Tkinter when using an IntVar, but by doing it yourself, you'll be able to decide what to do if the conversion fails instead of just getting a generic TclError.

HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in "U(17zX(%,5.z^5 (17l8(%,5.Z*(93-965$l7+-"])'
Jul 18 '05 #3
Pierre Quentel wrote:
Instead of indexing self.lab by strings, you can index them by the
attributes themselves : self.lab[self.i], and change line 23 into

for var in (self.s, self,i)

For your example, I wouldn't have used the "text" option in the
definition of the labels, then "textvariab le" in the callback method
(procedi) ; I would have used only "text" and no IntVar or StringVar,
just an integer and a string :

class MiaApp:
def __init__(self, genitore):
self.mioGenitor e = genitore
self.i = 42
self.s = "Baobab"
self.lab = {}
self.lab[self.i] = Label(self.mioG enitore)
self.lab[self.i].configure(widt h = 30, relief = RIDGE,
text = "[vuota]")
self.lab[self.i].pack()
self.lab[self.s] = Label(self.mioG enitore)
self.lab[self.s].configure(widt h = 30, relief = RIDGE,
text = "[vuota]")
self.lab[self.s].pack()
self.but = Button(self.mio Genitore)
self.but.config ure(text = "Vai!", command = self.procedi)
self.but.pack()
def procedi(self):
for var in (self.i, self.s):
self.lab[var].configure(text = var)

Regards,
Pierre


hi pierre.

i don't think this would not have worked as expected (by me). in my
intentions, the text of the label must be slaved to a variable, so that
it would change dynamically during the mainloop execution if another
part of the code had chenged the content of the variable.

maybe here is a more convincing example (the previous one was contrived
too hastily i guess):

1 from Tkinter import *
2
3 class MiaApp:
4 def __init__(self, genitore):
5 self.mioGenitor e = genitore
6 self.var = {0: 42, 1: "Baobab"}
7 self.lab = {}
8 self.lab[0] = Label(self.mioG enitore)
9 self.lab[0].configure(widt h = 30, relief = RIDGE,
10 text = "[vuota]")
11 self.lab[0].pack()
12 self.lab[1] = Label(self.mioG enitore)
13 self.lab[1].configure(widt h = 30, relief = RIDGE,
14 text = "[vuota]")
15 self.lab[1].pack()
16 self.but = Button(self.mio Genitore)
17 self.but.config ure(text = "Vai!", command = self.procedi)
18 self.but.pack()
19 self.but2 = Button(self.mio Genitore)
20 self.but2.confi gure(text = "Torna!", command =
self.procedi2)
21 self.but2.pack( )
22 def procedi(self):
23 for var in self.lab.keys() :
24 self.lab[var].configure(text = self.var[var])
25 def procedi2(self):
26 self.var[0] = 24
27 self.var[1] = "Cactus"
28
29 radice = Tk()
30 miaApp = MiaApp(radice)
31 radice.mainloop ()

in this example, when user presses "Torna!", the labels are not updated
as i expect; they only will be when user presses "Vai!" again (not what
i want).

thanks again

macs
Jul 18 '05 #4
Eric Brunel wrote:
On Tue, 29 Mar 2005 22:32:59 +0200, Pierre Quentel
<qu************ @wanadoo.fr> wrote:
[...]


mr brunel,

i thank you for prompt reply. i will take my time to read it carefully.

meanwhile, i inform you and the ng that someone else gave me a quick and
dirty answer to my problem, namely subststuting line #24 like this:

24 self.lab[var].configure(text variable = eval(var))

which seems to work as desired.

thanks again

bye

macs
Jul 18 '05 #5
Eric Brunel wrote:
On Tue, 29 Mar 2005 22:32:59 +0200, Pierre Quentel
<qu************ @wanadoo.fr> wrote:
Instead of indexing self.lab by strings, you can index them by the
attributes themselves : self.lab[self.i], and change line 23 into

for var in (self.s, self,i)

I really think this is asking for trouble: I suppose that the i and s
attributes are meant to change at some point in the future, and you're
mapping their *values* to the corresponding labels. So if the value
changes, you won't be able to get the label again.
For your example, I wouldn't have used the "text" option in the
definition of the labels, then "textvariab le" in the callback method
(procedi) ; I would have used only "text" and no IntVar or StringVar,
just an integer and a string :

I would have done exactly the contrary, as it is far more easier to use.
Using the textvariable option in Label's does not require you to
remember the labels, but only the variables used to hold their contents.
I'd also use two mappings: the first mapping a name to a Tkinter
variable for the label variables, and the second for the values to give
to these variables later.

Here is my version of the class code:

class MiaApp:
def __init__(self, genitore):
self.mioGenitor e = genitore
## Mapping for variables
self.variables = {
"i" : StringVar(),
"s" : StringVar()
}
## Mapping for future variable values
self.values = {
"i" : 42,
"s" : "Baobab"
}
## Now, create the labels
for var in self.variables. values():
## Default text
var.set("[vuota]")
## Create label
lb = Label(self.mioG enitore, width=30, relief=RIDGE,
textvariable=va r)
lb.pack()
## The button is no more remembered in an attribute, as it does
not seem to be needed
but = Button(self.mio Genitore, text = "Vai!", command =
self.procedi)
but.pack()

def procedi(self):
## Just change the variable values
for varName in self.variables. keys():
self.variables[varName].set(self.value s[varName])


your technique is most interirting and clean, i must say.

nevertheless, i cannot find a natural way to "modularize " it, in such a
way that the machinery of the method might be isolated from the code
that uses it.

consider for example the following two programs:

.....

$ cat Miodialogo.py
from Tkinter import *

class MioDialogo(Topl evel):
def __init__(self, genitore, chiamante):
Toplevel.__init __(self, genitore)
self.wm_title(" Valori delle variabili")

self.mioGenitor e = genitore
self.mioChiaman te = chiamante

self.fonteVar = ("Helvetica" , 14)

self.quadro_gra nde = Frame(self)
self.quadro_gra nde.pack(expand = YES, fill = BOTH)

self.titolo = Label(self.quad ro_grande)
self.titolo.con figure(
text = "Valori delle variabili:",
width = 20,
font = self.fonteVar
)
self.titolo.pac k(side = TOP, fill = X)

def mostraVariabili (self, *argomenti):
lung = 1
for i in argomenti:
if len(i) > lung:
lung = len(i)

self.dq = {}
self.dn = {}
self.dv = {}
for i in argomenti:
self.dq[i] = Frame(self.quad ro_grande)
self.dq[i].pack(
side = TOP,
anchor = W,
fill = X
)

self.dn[i] = Label(self.dq[i])
self.dn[i].configure(
text = i + ": ",
width = lung + 2,
anchor = W
)
self.dn[i].pack(
side = LEFT
)

self.dv[i] = Label(self.dq[i])
self.dv[i].configure(
textvariable = eval("self.mioC hiamante." + i),
anchor = W
)
self.dv[i].pack(
side = LEFT,
expand = YES,
fill = X
)

self.vaBene = Button(self.qua dro_grande)
self.vaBene.con figure(
text = "Va Bene",
command = self.pulsanteVa BenePremuto,
default = ACTIVE
)
self.vaBene.bin d(
"<Return>",
self.pulsanteVa BenePremuto_a
)
self.vaBene.foc us_force()
self.vaBene.pac k(
side = BOTTOM,
pady = 2
)

def pulsanteVaBeneP remuto(self):
self.destroy()
self.mioChiaman te.var.configur e(state = NORMAL)

def pulsanteVaBeneP remuto_a(self, evento):
self.pulsanteVa BenePremuto()

$ cat spunta-4.py
from Tkinter import *
from Miodialogo import *

class MiaApp:
def __init__(self, genitore):

self.mioGenitor e = genitore

self.fonte = ("Helvetica" , 12)

self.quadro_gra nde = Frame(genitore)
self.quadro_gra nde.pack(expand = YES, fill = BOTH)

self.msg = Label(self.quad ro_grande)
self.msg.config ure(
font = self.fonte,
wraplength = "10c",
justify = LEFT,
text = u"Sono qui sotto presentati tre pulsanti a spunta. \
Premendo un pulsante, se ne varia lo stato di selezione e si \
imposta una variabile a un valore che indica lo stato del \
pulsante stesso. Premendo il pulsante \u00ABMostra \
Variabili\u00BB si possono vedere i valori correnti delle \
variabili."
)
self.msg.pack(s ide = TOP)

self.pulsanti = Frame(self.quad ro_grande)
self.pulsanti.p ack(side = BOTTOM, fill = X, padx = "2m")

self.pulsanti_s punta = Frame(self.quad ro_grande)
self.pulsanti_s punta.pack(side = TOP, fill = X, padx = "2m")

self.annulla = Button(self.pul santi)
self.annulla.co nfigure(
text = "Annulla",
command = self.mioGenitor e.destroy
)
self.annulla.pa ck(side = LEFT, expand = YES)
self.var = Button(self.pul santi)
self.var.config ure(
text = "Mostra Variabili",
command = self.pulsanteMo straVariabiliPr emuto,
default = NORMAL
)
self.var.pack(s ide = LEFT, expand = YES)

self.tergicrist alli = IntVar()
self.b1 = Checkbutton(sel f.pulsanti_spun ta)
self.b1.configu re(
text = "Tergicrist alli a posto",
variable = self.tergicrist alli,
relief = FLAT
)
self.b1.pack(
side = TOP,
pady = 2,
anchor = W
)

self.freni = IntVar()
self.b2 = Checkbutton(sel f.pulsanti_spun ta)
self.b2.configu re(
text = "Freni a posto",
variable = self.freni,
relief = FLAT
)
self.b2.pack(
side = TOP,
pady = 2,
anchor = W
)

self.autista = IntVar()
self.b3 = Checkbutton(sel f.pulsanti_spun ta)
self.b3.configu re(
text = "Autista sobrio",
variable = self.autista,
relief = FLAT
)
self.b3.pack(
side = TOP,
pady = 2,
anchor = W
)

def pulsanteMostraV ariabiliPremuto (self):
if self.var.cget(" state") == ACTIVE:
self.var.config ure(state = DISABLED)
self.dialogo = MioDialogo(self .mioGenitore, self)
self.dialogo.mo straVariabili(" tergicristalli" ,
"freni",
"autista")

radice = Tk()
radice.wm_title ("Dimostrazi one Pulsanti a Spunta")
radice.wm_iconn ame("spunta")
miaApp = MiaApp(radice)
radice.mainloop ()

.....

the program spunta-4.py uses the module Miodialogo.py, which can be
usedby any other program simply passing along strings containing the
names of the attributes to be displayed.

i cannot find a similar way to modularize your technique (maybe it is my
fault).

thanks again

macs
Jul 18 '05 #6

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

Similar topics

3
2423
by: Ivan Letal | last post by:
I have just tried this code.. Tkinter import * root = Tk() def callback(event): print "clicked at", event.x, event.y frame = Frame(root, width=100, height=100)
2
4149
by: Irmen de Jong | last post by:
Hi, I'm having trouble with the code below. It's just a regular Tk text widget in which you can type and select text as expected, however the call to tkFileDialog.askopenfilename() seems to screw things up. After the file dialog, I can no longer use the Text widget (typing, selecting, it doesn't work anymore!) What am I doing wrong? TIA, --Irmen de Jong
2
3877
by: Russell E. Owen | last post by:
I want to support execution of simple user-written scripts in a Tkinter application. The scripts should be able to wait for data and such without hanging the GUI (and without having to write the script as a bunch of asynchronously called subroutines). I decided to use Tkinter's wait_variable. I built a "script runner" object that has suitable wait methods. Internally each of these methods registers a callback that sets a variable when...
2
991
by: Martin Jensen | last post by:
Hi I have a problem with Qt. My class definition is this: class Button : public QObject, public Tk_Object { Q_OBJECT public: Button() {} Button(Tk_Object &p); ~Button();
0
3578
by: syed_saqib_ali | last post by:
Below is a simple code snippet showing a Tkinter Window bearing a canvas and 2 connected scrollbars (Vertical & Horizontal). Works fine. When you shrink/resize the window the scrollbars adjust accordingly. However, what I really want to happen is that the area of the canvas that the scrollbars show (the Scrollregion) should expand as the window grows. It doesn't currently do this. although, if the window shrinks smaller than the...
2
4075
by: Stewart Midwinter | last post by:
this has me puzzled; I've created a small test app to show the problem I'm having. I want to use subprocess to execute system commands from inside a Tkinter app running under Cygwin. When I open a python interpreter and run my subprocess command, all is well. But when I run the same command from inside a Tkinter app, I'm getting errors.
0
2348
by: Stewart Midwinter | last post by:
I have a Tkinter app running on cygwin. It includes a Test menu item that does nothing more than fetch a directory listing and display it in a Toplevel window (I'd use a tkMessageBox showinfo widget, but for some reason the text is invisible on cygwin). After I close the Toplevel widget, all of the menus in my app behave as though they have no contents to them, i..e I can press on the File menu button, and see it depress, but the Exit...
2
5171
by: Andrew Trevorrow | last post by:
Our app uses embedded Python to allow users to run arbitrary scripts. Scripts that import Tkinter run fine on Windows, but on Mac OS X there is a serious problem. After a script does "root = Tk()" our app's menus are permanently changed in the following way: - The top item in the application menu changes to "About Tcl & Tk...". - The Quit item is disabled. - The File and Edit menus are completely replaced. - All further menus (except...
3
2000
by: H J van Rooyen | last post by:
Hi, Still struggling with my GUI exercise - I have the following lines of code in a routine that is bound at <Key-Returnto an instance of Entry : self.disp.Amount_des = Label(self.disp, text = self.dis_string, fg = 'black', bg = 'yellow') self.disp.Amount_des.grid(row = self.rownum, column=0, sticky = 'nesw')
4
2872
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
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7324
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
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
4151
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
4302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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
1953
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1611
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.