473,385 Members | 1,593 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Pass text variables to Labels in Tkinker GUI?

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.

4 6490
bvdet
2,851 Expert Mod 2GB
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
2,851 Expert Mod 2GB
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
2inshix
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
2inshix
11
Ok!

I tried it and it worked right away!

I'm a happy man!

Happy holidays everyone!
Dec 20 '11 #5

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

Similar topics

5
by: John | last post by:
I would like to pass array variables between URLs but I don't know how. I know its possible with sessions, but sessions can become useless if cookies are disabled. I have unsuccessfully tried...
6
by: Don | last post by:
How do I pass PHP variables to JavaScript in the returned browser page? Thanks, Don
3
by: Treetop | last post by:
I would like to pass text to a popup window to save creating a new html file for each help topic. I would like to have a value for the heading, a value for the text, code for printing the help...
1
by: John Cosmas | last post by:
I'm reusing my top and bottom borders by using placeholders. I need to pass public level variables from the parent to the child instead of using Session variables. How could I do that so that the...
1
by: Andy Roxburgh | last post by:
Hi, I have an monitoring application that displays various pieces of data, which are changing, on a tabpage within a form. The data is displayed in various different colours and the various...
0
by: Anton | last post by:
Hi All, I have a document management database that builds word documents based on templates. I use the following code to find and replace plain text variables defined by the user. Set rs =...
0
by: Anton | last post by:
Hi All, I would like to be able to check whether there are any remaining plain text variables left in a word document after it has been built based on a template. At this stage, I roll through a...
1
by: Bo Berglund | last post by:
Reposted with a better subject line. I am trying to port code from Delphi to C++ as described in a previous post titled: "How to swap bytes in variables (VS2005)???" Now I have run into a bit...
5
by: ofilha | last post by:
I have created a report in design mode. However, some of the fields i need are dynamic. That is, i have a series of fields text boxes mostly that must show up only as needed. I also have some...
1
by: kkshansid | last post by:
i want to pass both variables($q1 and value of select) from this php page to java script so that i can get both variables in second php file srt.php <script type="text/javascript"...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.