By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,435 Members | 2,891 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,435 IT Pros & Developers. It's quick & easy.

Pass text variables to Labels in Tkinker GUI?

P: 11
I'm trying to put together this GUI, it's my first attempt. It's mostly a collage of code I put together from samples I found here and there.

So, far so good, except I can't seem to be able to figure out how to pass "text variables" from an array to labels.

#If you go to def printLabels(self), and def on_move(), you will see what I mean:),

Thanks a million. (I'm just learnig to #program, sorry about the mess!)
Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/env python
  2. # -*- coding: cp932 -*-
  3. from Tkinter import *
  4. import tkMessageBox
  5.  
  6. #If you go to def printLabels(self) you will see my #question, thanks a million. (I'm just learnig to #program, sorry about the mess!)
  7. class GUIFramework(Frame):
  8.     """This is the GUI"""
  9.  
  10.     def __init__(self,master=None):
  11.         """Initialize yourself"""
  12.  
  13.         """Initialise the base class"""
  14.         Frame.__init__(self,master)
  15.  
  16.         """Set the Window Title"""
  17.         self.master.title("Parts-Weight Counting Application")
  18.         self.master.geometry("820x410+60+50")
  19.  
  20. #--------the radio buttons seect the language to be used on my labels
  21. #But I can't figure out how to pass the elements of the selected array to
  22. #my labels!
  23.  
  24.         """Display the main window with a little bit of padding"""
  25.         self.spanish=["Seleccione la pieza a contar",\
  26.                  "Proporcione el peso del contenedor/bolsa",\
  27.                  "Contar piezas","OK"]
  28.         self.english=["Select produt you want to count",\
  29.                  "Provide weight of container/bag",\
  30.                  "Count pieces","OK"]
  31.         self.japanese=[u"数えたい部品名を選択してください",\
  32.                  u"容器または袋の重さを記入してください",\
  33.                  u"清算開始",u"OK"]
  34.         self.grid(padx=20, pady=20,sticky=N+S+E+W)
  35.         self.CreateWidgets()
  36.  
  37.     def CreateWidgets(self):
  38.         """Create all the widgets that we need"""
  39.         """Create the Text"""
  40.         self.top=Frame(self)
  41.         self.top.grid(row=0, column=0)
  42.         self.frmLang=Frame(self.top)#language frame
  43.         self.frmLang.grid(row=0, column=0)#listbox frame
  44.         self.frmLbx=Frame(self.top)
  45.         self.frmLbx.grid(row=1, column=0,columnspan=2,sticky=N+S+E+W)
  46.         self.frmDlgBoxes=Frame(self.top)
  47.         self.frmDlgBoxes.grid(row=1, column=3,columnspan=2,sticky=(N, W, E, S))
  48.         self.frmDlgBoxes2=Frame(self.frmDlgBoxes)
  49.         self.frmDlgBoxes2.grid(row=3, column=5,columnspan=2,sticky=(N, W, E, S))
  50.         self.listBoxLb = Label(self.frmLbx, text="Select part name:")
  51.         self.listBoxLb.grid(row=3, column=0, sticky=W)
  52. #-----------------------------------------------------------------------
  53.  
  54.         self.labelTotalWeigt = Label(self.frmDlgBoxes,\
  55.                                      text="Enter total weight of parts:")
  56.         self.labelTotalWeigt.grid(row=1, column=1, sticky=E)
  57.  
  58.         #create labels
  59.         self.labelLngg = Label(self.frmLang, text='---', bg='yellow')
  60.  
  61.         #label dislaying array contents languages
  62.         self.labelLngg.grid(row=0, column=4,columnspan=2, pady=5)
  63. #--------------------------------------------------------------------------
  64.  
  65.         #create radiobtns
  66.         self.rb_v  = IntVar()
  67.         self.partWeight=float(.1000000)#IntVar()
  68.         self.lbParts=StringVar()
  69.         self.selection=StringVar()
  70.         self.label_text=StringVar()
  71.         self.result=list
  72.  
  73.  
  74.         self.id_rb_english = 101
  75.         self.rb_english = Radiobutton(self.frmLang, text='Englsih',\
  76.                                       value=self.id_rb_english, \
  77.                                       variable=self.rb_v, command=self.on_click)
  78.         self.rb_english.grid(row=0, column=0)
  79.  
  80.  
  81.         self.id_rb_spanish = 102
  82.         self.rb_spanish = Radiobutton(self.frmLang, text='Spanish',\
  83.                                       value=self.id_rb_spanish, \
  84.                                       variable=self.rb_v, command=self.on_click)                                     
  85.         self.rb_spanish.grid(row=0, column=1)
  86.  
  87.  
  88.         self.id_rb_japanese = 103
  89.         self.rb_japanese = Radiobutton(self.frmLang, text=u'日本語',\
  90.                                       value=self.id_rb_japanese, \
  91.                                       variable=self.rb_v, command=self.on_click)                                                                            
  92.         self.rb_japanese.grid(row=0, column=2)
  93.  
  94.  
  95.         """Create the ListBox"""
  96.         scrollbarV = Scrollbar(self.frmLbx, orient=VERTICAL)
  97.         #scrollbarH = Scrollbar(self, orient=HORIZONTAL)
  98.         #Create Listbox
  99.         self.lbParts = Listbox(self.frmLbx, selectmode=BROWSE
  100.                         , yscrollcommand=scrollbarV.set)
  101.         #self.lbSites2 = Listbox(self.frmLang, selectmode=BROWSE
  102.          #               , yscrollcommand=scrollbarV.set)
  103.         #self.text=self.on_move()
  104.         scrollbarV.grid(row=1, column=4, sticky=N+S)
  105.         scrollbarV.config(command=self.lbParts.yview)
  106.  
  107.         self.lbParts.grid(row=1, column=0, columnspan=4, sticky=N+W+S+E)
  108.         #self.lbSites2.grid(row=5, column=0, columnspan=4, sticky=N+W+S+E)
  109.         """Just fill up the listbox with some numbers"""
  110.         for i in range(50):
  111.             self.lbParts.insert(END, "Part No. %s"%i)
  112.         """Create the Add, Remove, Edit, and View Buttons"""
  113.         self.btnAdd = Button(self.frmLbx, text="Add")
  114.         self.btnAdd.grid(column=0, row=2, stick=E, pady=5)
  115.         self.btnRemove = Button(self.frmLbx, text="Remove")
  116.         self.btnRemove.grid(column=1, row=2, stick=E, pady=5)
  117.         self.btnEdit = Button(self.frmLbx, text="Edit")
  118.         self.btnEdit.grid(column=2, row=2, stick=E, pady=5)
  119.         self.btnView = Button(self.frmLbx, text="View",command=self.printLabels)
  120.         self.btnView.grid(column=3, row=2, stick=E, pady=5)
  121.         #create Entrybox
  122.         self.totalWeightParts = StringVar()
  123.         self.countedParts = StringVar()
  124.         self.container = StringVar()
  125.         self.container_entry = Entry(self.frmDlgBoxes, width=7,\
  126.                                      textvariable=self.totalWeightParts)
  127.         self.container_entry.grid(column=3, row=1, sticky=E)
  128.  
  129.         self.weight_entry = Entry(self.frmDlgBoxes, width=7,\
  130.                                   textvariable=self.container)
  131.         self.weight_entry.grid(column=3, row=0, sticky=E)
  132.  
  133.         self.btnCnt=Button(self.frmDlgBoxes, text="Count", command=self.calculate)
  134.         self.btnCnt.grid(column=3, row=8, sticky=E)
  135.         #create entry box listbox
  136.         # use entry widget to display/edit selection
  137.         self.enter1 = Entry(self.frmLbx, width=40, bg='blue',foreground="white")
  138.         self.enter1.insert(0, 'Select item')
  139.         self.enter1.grid(row=3, column=1)
  140.         # pressing the return key will update edited line
  141.         ##self.enter1.bind('<Return>', set_list)
  142.         # or double click left mouse button to update line
  143.         ##self.enter1.bind('<Double-1>', set_list)
  144.         #label results dialog
  145.         self.LabelShowPtsCtd=Label(self.frmDlgBoxes,\
  146.                                    textvariable=self.countedParts,\
  147.                                    bg='yellow').grid(column=3, row=7, sticky=(W, E))
  148.         self.Labelmgs=Label(self.frmDlgBoxes, text="Kg/mg").grid(column=4, row=0, sticky=W)
  149.         self.Labelmgs2=Label(self.frmDlgBoxes, text="Kg/mg").grid(column=4, row=1, sticky=W)
  150.  
  151.         self.LabelCntnrWgt=Label(self.frmDlgBoxes,\
  152.                          text="Enter container weight:").grid(column=1, row=0, sticky=E)
  153.         self.LabelTxtPtsCntd5=Label(self.frmDlgBoxes, \
  154.                          text="parts counted").grid(column=1, row=7, sticky=E)
  155.  
  156.         for child in self.frmDlgBoxes.winfo_children():
  157.             child.grid_configure(padx=5, pady=5)
  158.  
  159.         self.container_entry.focus()
  160.         self.weight_entry.focus()
  161.         self.frmDlgBoxes.bind('<Return>', self.calculate)
  162.         self.lbParts.bind('<ButtonRelease-1>', self.get_list)
  163.  
  164.     def get_list(self,*args):
  165.         """
  166.         function to read the listbox selection(s)
  167.         (mutliple lines can be selected)
  168.         and put the result(s) in a label
  169.         """
  170.         # tuple of line index(es)
  171.         self.selection = self.lbParts.curselection()[0]
  172.         self.seltext = self.lbParts.get(self.selection)
  173.         # delete previous text in enter1
  174.         self.enter1.delete(0, 50)
  175.         # now display the selected text
  176.         self.enter1.insert(0, self.seltext)
  177.         #self.label_text.set(self.seltext)
  178.         #print self.seltext,self.selection
  179.  
  180.  
  181.  
  182.     def calculate(self):
  183.         try:
  184.             self.value = float(self.totalWeightParts.get())
  185.             print self.value
  186.             print self.weight_entry.get()
  187.             print self.partWeight
  188.             self.countedParts.set((self.value - float(self.weight_entry.get()))\
  189.                                   /self.partWeight)
  190.         except ValueError:
  191.             pass
  192.     def on_click(self):
  193.         """radio button clicked, change results too"""
  194.         self.on_move()
  195.     def on_move(self,value=0):
  196.  
  197.         if self.rb_v.get() == self.id_rb_english:
  198.             self.result = self.english
  199.             #print self.result[0]
  200.         elif self.rb_v.get() == self.id_rb_spanish:
  201.             self.result = self.spanish
  202.             #print self.result[0]
  203.         else:
  204.             self.result = self.japanese
  205.             #print self.result[0]
  206. #---------------------------------------------------------------------------
  207.         #print self.result #this are the tags I want to use for my labels.
  208.         self.labelLngg['text'] =self.result[0]#How I can pass the value to this
  209.         #label, but It won't let me do the same other labels? eg. label below:
  210.         #self.LabelCntnrWgt['text'] =self.result[1]
  211. #---------------------------------------------------------------------------        
  212.     def printLabels(self):
  213.         #how do I pass these values to my labels? please m(_._)m
  214.         #To see printed results, select language and press the "View" button
  215.         print self.result[0]
  216.         print self.result[1]
  217.         print self.result[2]
  218.         print self.result[3]        
  219.         #pass
  220.  
  221. if __name__ == "__main__":
  222.     guiFrame = GUIFramework()
  223.     guiFrame.mainloop()
  224.  
  225.  
Dec 19 '11 #1

✓ answered by bvdet

There are two ways to update your labels. Use widget method w.config() to reassign a new label in your on_click() method. Alternatively, create Tkinter.StringVar objects and configure your Tkinter.Label objects with keyword textvariable instead of text and assign it to the appropriate variable. Reassign the value of the variables using StringVar method set() in your on_click() method.

Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
There are two ways to update your labels. Use widget method w.config() to reassign a new label in your on_click() method. Alternatively, create Tkinter.StringVar objects and configure your Tkinter.Label objects with keyword textvariable instead of text and assign it to the appropriate variable. Reassign the value of the variables using StringVar method set() in your on_click() method.
Dec 19 '11 #2

bvdet
Expert Mod 2.5K+
P: 2,851
Here's an example using a Tkinter.StringVar in combination with a Tkinter.Label.
Expand|Select|Wrap|Line Numbers
  1. import Tkinter
  2. from Tkconstants import *
  3. import time
  4.  
  5. textFont1 = ("Arial", 16, "bold")
  6.  
  7. class Clock(Tkinter.Frame):
  8.     def __init__(self, master):
  9.         self.master = master
  10.         menubar = Tkinter.Menu()
  11.         master.config(menu=menubar)
  12.         optionsMenu = Tkinter.Menu(tearoff=0)
  13.         menubar.add_cascade(label="Options", menu=optionsMenu)
  14.         optionsMenu.add_command(label='Print', command=self.print_value)
  15.         optionsMenu.add_command(label='Stop', command=self.destroy)
  16.         optionsMenu.add_command(label='Restart', command=self.start)
  17.         optionsMenu.add_command(label='Quit', command=master.destroy)
  18.         self.start()
  19.  
  20.     def start(self):
  21.         Tkinter.Frame.__init__(self, self.master)
  22.         self.pack(fill=BOTH, expand=1)
  23.         self.clockVar = Tkinter.StringVar(self.master)
  24.         self.clockLabel = Tkinter.Label(self, textvariable=self.clockVar,
  25.                                         relief="raised", font=textFont1,
  26.                                         bd=3,
  27.                                         bg='#ffffff000',
  28.                                         fg="#000000fff",
  29.                                         activebackground = "#000000fff",
  30.                                         activeforeground = "#ffffff000",
  31.                                         takefocus=1,
  32.                                         padx=3,
  33.                                         pady=3)
  34.         self.clockLabel.pack(fill=BOTH, expand=1)
  35.         self.run()
  36.  
  37.     def run(self):
  38.         timeStr = time.strftime("%A, %b %d, %Y\n%I:%M:%S %p\n%Z")
  39.         # 24 hour clock
  40.         #timeStr = time.strftime("%A, %b %d, %Y\n%X\n%Z")
  41.         if timeStr != self.clockVar.get():
  42.             self.clockVar.set(timeStr)
  43.         self.after(200, self.run)
  44.  
  45.     def print_value(self):
  46.         print self.clockVar.get()
  47.  
  48. if __name__ == "__main__":
  49.     root = Tkinter.Tk()
  50.     app = Clock(root)
  51.     root.mainloop()
  52.  
Dec 19 '11 #3

P: 11
thanks bvdet I think I understand but I won't know for sure until I give it a shot. I'll let you know how it went!

Cheers,

happy holidays.
Dec 20 '11 #4

P: 11
Ok!

I tried it and it worked right away!

I'm a happy man!

Happy holidays everyone!
Dec 20 '11 #5

Post your reply

Sign in to post your reply or Sign up for a free account.