1

It's my first program in python and I'm trying to create a program that will interface a MySql address book with a asterisk server and make a call. The "asterisk code part" is ok, I will add later, but the problem is that I have a listbox in Tkinter and I would like to fill it with values retrieved from a mysqldb query. I only can add a single value to the listbox, but if I make a print the results is correct. How can I solve this? I imagine that I will have to do a for loop. Later I will have to know how select a value from the list and store in a variable.

from Tkinter import *
import MySQLdb
root = Tk()
root.title("PyCall")
myContainer = Frame(root)
myContainer.pack(side=TOP, expand=YES, fill=BOTH)

db = MySQLdb.connect("localhost",port=3306, user="root", passwd="mypass", db="test" )
cursor = db.cursor()

cursor.execute("SELECT * FROM utenti")
db.commit()

numrows = int(cursor.rowcount)
for x in range(0,numrows):
    row = cursor.fetchone()
    print row[1]

listbox = Listbox(root)
listbox.pack()
listbox.insert(END, row[1])

root.mainloop()
db.close()

1 Answer 1

2

If that's your first program in Python, you're off to a good start! Your question really has little to do with MySQL, and you seem to have a good handle on that, so I'll leave that alone and just focus on the Tkinter issues you are having. I don't have a MySQL database to test with anyway :)

It's generally a good idea in GUI applications, at least in Tkinter, to setup your own application class with a Tk root frame as the application's master container. The reason for this is that GUIs are a always a bit of slight of hand, they are only a facade for real application data, and that real data needs someplace to live. By creating your own application class, you have a home for that data via self.

Okay, enough with all the boring stuff, let's just build something:

import Tkinter


class Application(Tkinter.Frame):
    def __init__(self, master):
        Tkinter.Frame.__init__(self, master)
        self.master.minsize(width=256, height=256)
        self.master.config()
        self.pack()

        self.main_frame = Tkinter.Frame()

        self.some_list = [
            'One',
            'Two',
            'Three',
            'Four'
        ]

        self.some_listbox = Tkinter.Listbox(self.main_frame)

        # bind the selection event to a custom function
        # Note the absence of parentheses because it's a callback function
        self.some_listbox.bind('<<ListboxSelect>>', self.listbox_changed)
        self.some_listbox.pack(fill='both', expand=True)
        self.main_frame.pack(fill='both', expand=True)

        # insert our items into the list box
        for i, item in enumerate(self.some_list):
            self.some_listbox.insert(i, item)

        # make a label to show the selected item
        self.some_label = Tkinter.Label(self.main_frame, text="Welcome to SO!")
        self.some_label.pack(side='top')

        # not really necessary, just make things look nice and centered
        self.main_frame.place(in_=self.master, anchor='c', relx=.5, rely=.5)

    def listbox_changed(self, *args, **kwargs):
        selection_index = self.some_listbox.curselection()
        selection_text = self.some_listbox.get(selection_index, selection_index)
        self.some_label.config(text=selection_text)

root = Tkinter.Tk()
app = Application(root)
app.mainloop()

Hope this helps, and have fun building GUIs!

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Pathétique your code is working very well! Now I must insert in self.some_list [...] the query or the query results. I've tried but without success. Please help a poor noob!
I just used a regular Python list, you can add items using append. See the Python docs.
The interpreter tells me that listbox has not 'append' attribute
self.some_list is a Python list object and can be added to using append, self.some_listbox is a Tkinter.Listbox object and items can be added using insert given the index where you want to insert the string and the string to insert...like in my for loop above.
Solved! I changed the code in this way: self.some_list = [ 'ADDRESS BOOK' ] db = MySQLdb.connect("localhost",port=3306, user="root", passwd="mypass", db="test" ) cursor = db.cursor() cursor.execute("SELECT name FROM users") db.commit() numrows = int(cursor.rowcount) for i in range(0,numrows): row = cursor.fetchone() if (row): self.some_list.append(row[0]) Thank you for the help! I am really grateful
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.