L
L
lavagod2020-06-24 19:03:48
Python
lavagod, 2020-06-24 19:03:48

How to make a button call two functions?

Hello

Full code:
Database wdfiles.ru/jb6d
Script wdfiles.ru/jb6e

I write database processing in Python + Tkinter. The almost complete code for the project is here:

# Подключение библиотек
import sqlite3                              # Подключить SQLite3
from tkinter import *                       # Подключить tkinter
from tkinter.ttk import Combobox            # Подключить раскрывающийся список
from tkinter import scrolledtext            # Подключить скроллируемый текст

# Основные параметры и переменные
root = Tk()                                 # Tk = окно приложения
root.title("База данных")                   # Определить заголовок
root.geometry("800x600")                    # Определить размеры
dbase = sqlite3.connect('users2.db')        # dbase = база данных "users.db"
cursor = dbase.cursor()                     # cursor = курсор базы данных

def return_table_name():
    number = combo.get()                                    # number = выбранная таблица (как в списке)
    if number == 'Пользователи':    table_name = 'table1'   # table_name = table1
    elif number == 'Клиенты':       table_name = 'table2'   # table_name = table2
    elif number == 'Продукты':      table_name = 'table3'   # table_name = table3
    return table_name

def show():
    table_name = return_table_name()                        # table_name = реальное имя выбранной таблицы
    sql = "SELECT * FROM {}".format(table_name)             # sql = взять все из выбранной таблицы
    data = cursor.execute(sql)                              # data = выполнить запрос (sql)
    names = list(map(lambda x: x[0], data.description))     # name = заголовки полей запроса
    temp = " \t\t".join(map(str,names)) + "\n\n"            # temp = заголовок1 \t\t заголовок2 ...
    for i in data:                                          # Пройдем в цикле по запросу
        temp += " \t\t".join(map(str,i)) + "\n"             # temp += одна запись как строка
    txt.delete(1.0, END)                                    # txt = ""
    txt.insert(INSERT, temp)                                # txt = temp

def add_line():
    pass

def del_line():
    table_name = return_table_name()
    del_id = entry1.get()
    sql = "DELETE FROM {} WHERE id={}".format(table_name, del_id)
    cursor.execute(sql)
    dbase.commit()

# Основная программа: верхние элементы управления
combo = Combobox()
combo['values'] = ('Пользователи', 'Клиенты', 'Продукты');  combo.place(x=10, y=10)
show = Button(text="Показать", command=show);               show.place(x=200, y=10)
txt = scrolledtext.ScrolledText(width=100, height=20);      txt.place(x=10, y=50)

# Основная программа: нижние элементы управления
add_line = Button(text="Добавить", command=lambda: (add_line(), show()));  add_line.place(x=10, y=370)

# ======================================================================================================
del_line = Button(text="Удалить", command=lambda: (del_line(), show()));   del_line.place(x=200, y=400)
# ======================================================================================================

entry1 = Entry(); entry1.place(x=10, y=400)
entry2 = Entry(); entry2.place(x=10, y=420)
entry3 = Entry(); entry3.place(x=10, y=440)
entry4 = Entry(); entry4.place(x=10, y=460)

root.mainloop()


When deleting a record by id, I want the "Delete" button to do two things: 1) call del_line() and 2) call show(). I found information that this should be done through lambda (and it used to work in previous projects), but now an error is

generated File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
return self.func( *args)
File "users2.py", line 52, in
del_line = Button(text="Delete", command=lambda: (del_line(), show())); del_line.place(x=200, y=400)
TypeError: 'Button' object is not callable

Something Python doesn't like about this call. I highlighted the buggy line `del_line =... ` at the bottom of the code. Tried without brackets after function names = likewise no. Where to think? What tell me?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JktuJQ, 2020-06-24
@JktuJQ

I would venture to guess (did not check), but the error is in the names of the button and the del_line function. When you try to initialize the button, the error Button object is not callable is raised. the interpreter tries to call the button itself, not the function of the same name. Try changing the name of the button or function, it should help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question