Python - Select clickable

0

I have to display on the screen (Tkinter) a list drawn from the database (mysql) containing information about a person (name and id) and make it possible for any item in this list to be clickable and, select that person's id and call another function then. How to do this in Python?

    
asked by anonymous 26.07.2018 / 14:44

2 answers

0

The code below uses sqlalchemy to create a table in the database and enter random names, then use tkinter to show a list of these names, and clicking displays the selected name.

BANCO_DE_DADOS = 'mysql://root:password@localhost/nomedobanco'

import sqlalchemy as sa
from sqlalchemy import Column, Unicode, Integer, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

import tkinter as tk
import tkinter.messagebox as tkmsg

Base = declarative_base()
Session = sessionmaker()

class Pessoa(Base):
    __tablename__ = 'pessoas'
    id = Column(Integer(), primary_key=True)
    nome = Column(Unicode(300))

def inicializa_banco(engine):
    Base.metadata.bind = engine
    Base.metadata.create_all()
    Session.configure(bind=engine)

def cria_pessoas_de_teste(num_pessoas=10):
    import random
    import itertools
    nomes = ['Bruno', 'Cláudio', 'Alfredo', 'João']
    sobrenomes = ['Costa', 'Almeida', 'Souza', 'Teixeira']
    nomes_completos = [' '.join(g) for g in itertools.product(nomes, sobrenomes)]
    for n in random.sample(nomes_completos, num_pessoas):
        yield Pessoa(nome=n)

class App:
    def __init__(self, parent):
        self.parent = parent
        self.combo()

    def combo(self):
        self.box_value = tk.StringVar()
        self.box = tk.Listbox(self.parent)
        self.box.bind('<<ListboxSelect>>', self.selecionou)
        s = Session()
        for p in s.query(Pessoa):
            self.box.insert(tk.END, '{0.id} - {0.nome}'.format(p))
        s.close()
        self.box.grid(column=0, row=0)

    def selecionou(self, evt):
        pos = int(self.box.curselection()[0])
        pessoa = self.box.get(pos)
        tkmsg.showinfo(title='Selecionado!', message='Você selecionou {}'.format(pessoa))

if __name__ == '__main__':
    engine = create_engine(BANCO_DE_DADOS, echo=True)
    inicializa_banco(engine)
    s = Session()
    s.add_all(cria_pessoas_de_teste())
    s.commit()
    root = tk.Tk()
    app = App(root)
    root.mainloop()

Remembering that, in order to work, you have to edit the line with the name of the bank, user and password.

    
26.07.2018 / 16:07
0

Some inward considerations, regardless of whether you've already decided to use tkinter: if it's a real problem to solve, not a learning exercise, you first have to choose what technology to use for your interface program: it can be a desktop application, which opens a local window itself, or it can be a web application.

In the second case, your program runs, and runs in the background, but does not create anything on the screen directly. A web browser on the same computer points to a port on the computer itself, provided by the framework used by your program - and everything your program has to provide is well-formatted HTML, with <a ...> link elements to another view function that can provide the details.

It may scare you if you've never done anything like it, but this is the easiest way - even if after that, people can use your program from other computers on the same network, or even on the Internet, without having to install nothing locally.

I would suggest using the Flask micro-framework - take the tutorial, and you will find it easy to get to where you want: link

The other way I mentioned, with a direct application, requires the use of a library with a graphical toolkit - which may be tkinter, which comes installed with Python itself.

Its initial simplicity can hide many inherent problems of graphical interface development, that HTML solves well, separating presentation logic - in HTML you create simple m document, and then you can arrange layout with CSS without worry with the logic of your program. To begin with, even if you do a legal tkinter tutorial or another toolkit such as GTK + or Qt, the tutorial will hardly cover usage examples in conjunction with a database, and how to have clickable on-screen data elements.

By the way, most of the tutorials and documentation from tkinter and other graphic libraries suffers from an addiction that greatly complicates development: everyone insists on creating their program as a class that inherits directly from the Window class or another equivalent of the toolkit graphic. This is unnecessary - your program has a window, it is not a window - it is perfectly possible to write this without the use of user-created classes.

Begin creating a main function that creates the desired window and components (such as frames, navigation buttons, etc.) as normal variables. I suggest using the complementary external library "ttk" that has the "treeview" widget - without it you will have to re-invent the wheel to make a list of scrollable scrollable elements: link

In short, it is not impossible to do in tkinter - but I also can not create the zero program for you in this answer. If you opt for this, please start your code by creating the window skeleton, desired layout using frames, etc ... and me or someone else here can give you more tips.

    
26.07.2018 / 15:05