Форум программистов, компьютерный форум, киберфорум
Python: GUI, графика
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.60/25: Рейтинг темы: голосов - 25, средняя оценка - 4.60
0 / 0 / 0
Регистрация: 23.11.2020
Сообщений: 11
PyQt5

'QPushButton' object is not callable

12.11.2021, 02:16. Показов 5008. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import sys
import sqlite3
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QListWidgetItem
 
 
class CoffEEE(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi('coffEEE_project.ui', self)
        self.look_for_button.clicked.connect(self.coffee_search)
        self.choose_coffee_button.clicked.connect(self.coffee_fetch)
        self.disadvant_button(self.disadvant_b())
        self.advant_button(self.advant_b)
        self.advantages_all = ("1. Coffee boosts your physical performance. "
                               "2. Coffee may help you lose weight."
                               "3. Coffee helps you burn fat. "
                               "4. Coffee helps you focus and stay alert. "
                               "5. Coffee lowers risk of death."
                               "6. Coffee reduces risk of cancers."
                               "7. Coffee reduces risk of stroke."
                               "8. Coffee reduces risk of Parkinson’s disease."
                               "9. Coffee protects your body."
                               "10. Coffee may lower risk of Type II diabetes."
                               "11. Coffee protects your brain."
                               "12. Coffee brightens your mood, helps fight depression and lowers risk of suicide.")
        self.disadvantages_all = ("1. Bad coffee can be toxic."
                                  "2. Coffee can kill you."
                                  "3. Coffee can cause insomnia and restlessness."
                                  "4. Don’t drink more than one cup a day if you’re pregnant."
                                  "5. If you have high cholesterol please choose filtered coffee."
                                  "6. Coffee for kids, may increase bedwetting.")
 
        self.connection = sqlite3.connect("coffEEE.db", check_same_thread=False)
        self.cursor = self.connection.cursor()
 
        self.all_comp = [
            "milk", "corn", "water", "whipped_milk",
            "whipped_cream", "milk_and_cream",
            "whiskey", "ice", "chocolate",
            "honey", "syrup"
        ]
 
        self.components_dict = {
            self.milk: "Milk",
            self.corn: "Corn",
            self.whipped_milk: "Whipped milk",
            self.whipped_cream: "Whipped cream",
            self.milk_and_cream: "Milk and cream",
            self.whiskey: "Whiskey",
            self.ice: "Ice",
            self.chocolate: "Chocolate",
            self.honey: "Honey",
            self.syrup: "Syrup"
        }
 
    def coffee_search(self):
        self.needed_components_list_widget.clear()
        part_of_query = f""
 
        for component_object, text in self.components_dict.items():
            if not component_object.isChecked():
                continue
            self.needed_components_list_widget.addItem(text)
            part_of_query += f"AND components.component_name='{text.lower().replace(' ', '_')}'"
 
        if part_of_query:
            full_query = f"""
            SELECT DISTINCT coffee.id, coffee.name, coffee.description
            FROM coffee
            LEFT JOIN coffees_variations ON coffees_variations.id_coffee = coffee.id
            LEFT JOIN components ON components.id = coffees_variations.id_component
            WHERE {part_of_query[3:]};
            """
        else:
            full_query = """
            SELECT DISTINCT coffee.id, coffee.name, coffee.description
            FROM coffee
            LEFT JOIN coffees_variations ON coffees_variations.id_coffee = coffee.id
            LEFT JOIN components ON components.id = coffees_variations.id_component;
            """
 
        self.cursor.execute(full_query)
        self.available_coffee_list_widget.clear()
        result = self.cursor.fetchall()
        if not result:
            dialog = QMessageBox(
                self,
                text="Кратче говоря, нет кофеёчков с таким чаем"
            )
            dialog.show()
            return
 
        for (_id, name, _) in result:
            self.available_coffee_list_widget.addItem(f"{_id}. {name}")
 
    def coffee_fetch(self):
        item: QListWidgetItem
        item = self.available_coffee_list_widget.currentItem()
        if not item:
            return
 
        self.cursor.execute(f"""
        SELECT component_name 
        FROM components 
        LEFT JOIN coffees_variations ON components.id = coffees_variations.id_component
        LEFT JOIN coffee ON coffee.id = {item.text().split(" ")[0]};
        """)
        self.needed_components_list_widget.clear()
        res = self.cursor.fetchall()
        if not res:
            return
 
        for (comp_name,) in res:
            self.needed_components_list_widget.addItem(comp_name)
 
    def advant_b(self):
        dialog = QMessageBox(
            self,
            text="1. Coffee boosts your physical performance. "
                 "2. Coffee may help you lose weight."
                 "3. Coffee helps you burn fat. "
                 "4. Coffee helps you focus and stay alert. "
                 "5. Coffee lowers risk of death."
                 "6. Coffee reduces risk of cancers."
                 "7. Coffee reduces risk of stroke."
                 "8. Coffee reduces risk of Parkinson’s disease."
                 "9. Coffee protects your body."
                 "10. Coffee may lower risk of Type II diabetes."
                 "11. Coffee protects your brain."
                 "12. Coffee brightens your mood, helps fight depression and lowers risk of suicide."
        )
        dialog.setWindowTitle("Плюсы кофе")
        dialog.show()
        return
 
    def disadvant_b(self):
        dialog1 = QMessageBox(
            self,
            text="1. Bad coffee can be toxic."
                 "2. Coffee can kill you."
                 "3. Coffee can cause insomnia and restlessness."
                 "4. Don’t drink more than one cup a day if you’re pregnant."
                 "5. If you have high cholesterol please choose filtered coffee."
                 "6. Coffee for kids, may increase bedwetting."
        )
        dialog1.setWindowTitle("Минусы кофе")
        dialog1.show()
        return
 
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = CoffEEE()
    ex.show()
    sys.exit(app.exec_())
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
12.11.2021, 02:16
Ответы с готовыми решениями:

TypeError: 'list' object is not callable
from tkinter import * window = Tk() a=,,,,,,,,,,,] c=,,,,,,,,,] for i in range(9): for j in range(9): ...

Object is not callable with class
День добрый! Не знаю почему, python 3 выдает ошибку if (self.context_name(line)): TypeError: 'str' object is not callable ...

'dict' object is not callable
Добрый день! Это не вопрос, просто хочу поделиться. Возникло такая ситуация при попытке объединить два словаря: TypeError: 'dict'...

1
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7390 / 4817 / 1246
Регистрация: 30.03.2015
Сообщений: 13,664
Записей в блоге: 29
12.11.2021, 09:55
Цитата Сообщение от Kretsu Mika Посмотреть сообщение
'QPushButton' object is not callable
ну так как ты поленился привести весь текст ошибки то вот ответ - не надо пробовать вызывать объект баттон, то есть писать его с круглыми скобками. Что это за объект и где он -ищи по строке, указанной в ошибке.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
12.11.2021, 09:55
Помогаю со студенческими работами здесь

str' object is not callable
Пишу FeedBack бота для ВУЗа. Есть пару проблем: 1. При команде /mail не меняется тема сообщения. 2. Возникает ошибка " 'str' object is...

'int' object is not callable
import math #горизонтальная координата x = 1 #ускорение свободного падения g = 9.822 #начальное положение мяча y0 = 1 ...

'list' object is not callable
Не могу разобраться в свойствах: По заданию в пустой список добавлять элементы через свойство class employee: def __init__():...

'Str' object is not callable
Пишу бота, столкнулся с этой ошибкой - 'str' object is not callable. Не могу понять в чем проблема, ошибка выходит на этапе регистрации, но...

'QueryDict' object is not callable
def new_user_registration (request): errors = if 'user' and 'pass' and 'email' and 'pass2' in request.GET: pass1 =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru