Question

I have a SQLite dabatase file, and a python file which contains multiple button made by tkinter. What I want to do is to read a different row with different button by using only one function.

What I get currently is all the rows being printed without even pressing a button,, I really need help and will be grateful

import Tix as tk from Tkinter import * import sqlite3 as lite import
sys

def show_POI():

    POI= tk.Tk()
    POI.geometry("%dx%d+%d+%d" %(320,240,0,0))
    POI.title("Points Of Interest")
    menu=tk.Button(POI, height=1, width=5, text='Menu')
    menu.pack()
    label = tk.Label(POI)
    label.pack()
    sw= tk.ScrolledWindow(POI, scrollbar=tk.Y) # just the vertical scrollbar
    sw.pack(fill=tk.BOTH, expand=1)
    con = lite.connect('databaseDB.sqlite')
    with con:
        cur = con.cursor()
        cur.execute("SELECT * FROM Location")
        result = cur.fetchall()

        def show_info(x):
            cur.execute("SELECT * FROM Location WHERE ID = "+str(x)+"")
            result = cur.fetchall()
            print result
            return result

        i=1

        for row in result:
            text = row[1]
            e=tk.Button(sw.window,height=2,width=40,text=text,anchor=W,
command=show_info(i))
            e.pack()
            i=i+1

    POI.mainloop()

show_POI()
Was it helpful?

Solution

You're currently calling show_info() before creating the button, which is why it prints the results for each iteration of the loop. You can use a lambda expression to pass an argument, and assign a default argument of i to each command (otherwise only the last known value of i will be set to each button)

e=tk.Button(sw.window,height=2,width=40,text=text,anchor=W,
            command=lambda i=i: show_info(i))

That should fix that problem, but one other thing to mention is that you can remove return result from the show_info() function, because it's not returning to anything. Hope that helps.

More about buttons and callbacks: http://effbot.org/zone/tkinter-callbacks.htm

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top