Thread: python/tkinter

    #1
  1. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2001
    Posts
    606
    Rep Power
    35

    python/tkinter


    I seem to be having trouble clearing previous text from a label while printing new text.
    I've tried using destroy but, keep getting an error.

    Any help would be great...

    Code:
    import tkinter as tki
    import pymysql
    import string
    
    alphabet = string.ascii_uppercase
    
    class MyApp(object):
        def __init__(self,root):
            self.root = root
    
    
            i=0
            for letter in enumerate(alphabet):
                button = tki.Button(text=letter[1],font="verdana",command=lambda letter=letter[1]:self.getNames(letter)).grid(column=i,row=0,padx=3,pady=8,ipady=2,ipadx=2)
                i=i+1
    
    
            
        def getNames(self,letter):
            db = pymysql.connect(host="192.168.1.102",user="me",passwd="mypass",db="recipes")
            cursor = db.cursor()
            query = "select name from cook where name like '" + letter +"%'"
            cursor.execute(query)
    
            
            i=4
            for n in cursor:
                self.label = tki.Label(text=str.upper(n[0])).grid(columnspan=26,row=i,sticky="W")
                i=i+1
            db.close()
    
    root = tki.Tk()
    myapp = MyApp(root)
    root.mainloop()
    Last edited by menator; May 24th, 2015 at 01:03 PM.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    667
    Rep Power
    40
    Use label_id["text"]="new string" to change the text for a label. However there are too many errors to proceed.

    1, The line starting with "self.label=" will error so the program won't run.
    2. Geometry managers, including grid(), return None so self.label always contains None
    3. self.label will overwrite the previous Tkinter ID, so there is no way to access individual labels, except for the last one created.

    Start with one label and get it to work and then add others.
    Last edited by dwblas; May 24th, 2015 at 01:17 PM.
  4. #3
  5. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,981
    Rep Power
    510
    Awesome gif, menator.

    first idea: assuming you query the database several times during a session with one instance of MyApp, I'd not spend so much time opening and closing the database. I'm pretty sure pymysql supports contexts, pending tests, I'd design the code to use the context.

    second idea: generate the labels once, store them, change their text attribute. Well, we don't know ahead of time how many labels there are, so maybe it's not a good idea.

    Errors in your program:
    • did not use root as the master of Button and Label widgets. Might have caused the symptom you experienced. The root cause, if you will.
    • saving button=tki.Button(...).grid(...) is not purposeful.
    • code shows no comprehension of enumerate function. for letter in enumerate(alphabet)text=letter[1]
      In the interpreter, practice with
      for (i,x,) in enumerate('abcde'): print('i is {} and x is {}'.format(i,x,))


    I'd think this is a better program. I've substituted a random length list to simulate the result of your database query.
    Code:
    import tkinter
    import random
    #import pymysql
    import string
    
    alphabet = string.ascii_uppercase
    
    class MyApp(object):
    
        def __init__(self,root,cursor):
            self.root = root
            self.cursor = cursor
            gd = dict(row=0,padx=3,pady=8,ipady=2,ipadx=2)
            for (i, letter,) in enumerate(alphabet):  # you didn't understand enumerate
                if letter == 'Q':
                    command = root.quit
                    text = 'Quit'
                else:
                    command = lambda letter=letter:self.getNames(letter)
                    text = letter
                tkinter.Button(root, text=text,font="verdana",command=command).grid(column=i,**gd)
            self.labels = []
    
        def getNames(self,letter):
            #cursor = self.cursor
            #query = "select name from cook where name like '" + letter +"%'"
            #cursor.execute(query)
            root = self.root
            cursor = list(range(random.randint(0,10)))
            labels = self.labels
            ld = dict(master=root, text='glorp', font=("verdana",18,))
            while len(labels) < len(cursor):
                labels.append(tkinter.Label(**ld))
                labels[-1].grid(columnspan=26,row=len(labels),sticky="W")
            for (label, message,) in zip(labels,cursor,):
                label.config(text = letter+str(message))
            for i in range(len(cursor),len(labels)): # remove offending text
                labels[i].config(text = '') # set state disabled?
    
    def main():
        root = tkinter.Tk()
        #with pymysql.connect(host="192.168.1.102",
        #                     user="me",
        #                     passwd="mypass",
        #                     db="recipes").cursor() as cursor:
        #     MyApp(root, cursor)
        #     root.mainloop()
        persist = MyApp(root, None)
        root.mainloop()
        root.destroy()
    
    if __name__ == '__main__':
        main()
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2001
    Posts
    606
    Rep Power
    35
    Thanks guys. I've not worked with python much. I'm trying to get a basic understanding. Thanks again for giving me something to work with.

IMN logo majestic logo threadwatch logo seochat tools logo