Bool object is not callable ошибка

The TypeError ‘bool’ object is not callable occurs when you try to call a Boolean by putting parenthesis () after it like a function. Only functions respond to function calls.

This tutorial will go through the error in detail and how to solve it with the help of code examples.


Table of contents

  • TypeError: ‘bool’ object is not callable
  • Example
    • Solution
  • Summary

TypeError: ‘bool’ object is not callable

Calling a function means the Python interpreter executes the code inside the function. In Python, we can only call functions. We can call functions by specifying the name of the function we want to use followed by a set of parentheses, for example, function_name(). Let’s look at an example of a working function that returns a string.

# Declare function

def simple_function():

    print("Learning Python is fun!")

# Call function

simple_function()
Learning Python is fun!

We declare a function called simple_function in the code, which prints a string. We can then call the function, and the Python interpreter executes the code inside simple_function().

Bool type objects do not respond to a function call because they are not functions. If you try to call a Bool type object if it were a function, the Python interpreter will raise the TypeError: ‘bool’ object is not callable.

We can verify if an object is callable by using the built-in callable() method and passing the object to it. If the method returns True, then the object is callable, otherwise, if it returns False the object is not callable. Let’s look at testing the method with a Boolean:

a_bool = True

print(callable(a_bool))
False

The callable function returns false for a Boolean, verifying that bool objects are not callable.

Example

Let’s look at an example where we define a function that checks if a number is a prime number. We will use this function to check if a list of numbers contains prime numbers. First, let’s look at the function, which we will call prime_number.

def prime_number(num):

    # Is prime number flag

    is_prime = False

    # Prime numbers are greater than 1

    if num > 1:

        # Check for factors

        for i in range(2, num):

            #If factor is found, set is_prime to True

            if (num % i) == 0:

                is_prime = True

                # break out of the loop

                break

    return is_prime

The function takes in one argument, which is the number we want to check, and returns True if the number is prime and False if it is not. Next, we will iterate over a list of numbers and pass each number to a prime_number function call.

lst = [4, 7, 12, 17, 23, 44]

for i in lst:

    prime_number = prime_number(i)

    print(f'Is {i} Prime? {prime_number}')

Let’s run the code to see what happens:

Is 4 Prime? False
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-cb5177ccdebb> in <module>
      2 
      3 for i in lst:
----> 4     prime_number = prime_number(i)
      5     print(f'Is {i} Prime? {prime_number}')

TypeError: 'bool' object is not callable

We get a TypeError because the variable prime_number has the same name as the function we want to call. The variable gets assigned a Boolean value for the first loop.

Because the variable has the same name as the function, the Boolean value overrides the function.

Then, in the second loop, when we try to call the prime_number() function we are calling the Boolean value from the previous loop instead.

We can verify the override by checking the type of prime_number using type().

lst = [4, 7, 12, 17, 23, 44]

for i in lst:

    print(type(prime_number))

    prime_number = prime_number(i)

    print(type(prime_number))

    print(f'Is {i} Prime? {prime_number}')
<class 'function'>
<class 'bool'>
Is 4 Prime? True
<class 'bool'>

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-5ba50fe7142f> in <module>
      3 for i in lst:
      4     print(type(prime_number))
----> 5     prime_number = prime_number(i)
      6     print(type(prime_number))
      7     print(f'Is {i} Prime? {prime_number}')

TypeError: 'bool' object is not callable

We see that at the start of the loop, prime_number is a function, and then after the first call prime_number is Boolean. Then at the start of the second loop, when we want to make a function call, prime_number is still a Boolean.

Solution

To solve this error, we need to use a distinct variable name. We will choose is_prime instead of prime_number. If you are using IPython, ensure you start from a new session or redefine the prime_number function. Let’s look at the revised code:

lst = [4, 7, 12, 17, 23, 44]

for i in lst:

    is_prime = prime_number(i)

    print(f'Is {i} Prime? {is_prime}')

Let’s run the code to see the result:

Is 4 Prime? True
Is 7 Prime? False
Is 12 Prime? True
Is 17 Prime? False
Is 23 Prime? False
Is 44 Prime? True

We can also verify that prime_number stays as a function during the entire program lifecycle:

lst = [4, 7, 12, 17, 23, 44]

for i in lst:

    print(type(prime_number))

    is_prime = prime_number(i)

    print(type(prime_number))

    print(f'Is {i} Prime? {is_prime}')

Let’s run the code to see the result:

<class 'function'>
<class 'function'>
Is 4 Prime? True
<class 'function'>
<class 'function'>
Is 7 Prime? False
<class 'function'>
<class 'function'>
Is 12 Prime? True
<class 'function'>
<class 'function'>
Is 17 Prime? False
<class 'function'>
<class 'function'>
Is 23 Prime? False
<class 'function'>
<class 'function'>
Is 44 Prime? True

Summary

Congratulations on reading to the end of this tutorial. The TypeError ‘bool’ object is not callable occurs when you try to call a Boolean as if it were a function. TypeErrors occur when you attempt to perform an illegal operation for a specific data type.

To solve this error, ensure that the variable names and function names are distinct and that there are no parentheses after Boolean values. You can check if an object is a Boolean by using the built-in type() method.

For further reading on not callable TypeErrors, go to the articles:

  • How to Solve Python TypeError: ‘tuple’ object is not callable.
  • How to Solve Python TypeError: ‘DataFrame’ object is not callable.

To learn more about Python, specifically for data science and machine learning, go to the online courses page on Python.

Have fun and happy researching!

Cover image for How to fix "‘bool’ object is not callable" in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The “TypeError: ‘bool’ object is not callable” error occurs when you try to call a boolean value (bool object) as if it was a function!

Here’s what the error looks like:

Traceback (most recent call last):
  File /dwd/sandbox/test.py, line 3, in <module>
    if is_active() == true:
       ^^^^^^^^^^^
TypeError: 'bool' object is not callable

Enter fullscreen mode

Exit fullscreen mode

In the simplest terms, this is what happens:

is_active = True

# ⚠️ is_active is a boolean value not a callable
if is_active() == True:
    print('User is active.')

Enter fullscreen mode

Exit fullscreen mode

Calling a boolean value like a callable isn’t what you’d do on purpose, though. It usually happens due to unwanted value assignments. Or accidentally overriding a function’s global name with True or False!

To fix the issue, trace the error back up to the statement that changed your function to a boolean value.

Additionally, if you accidentally put an extra parenthesis after a built-in or user-defined function that returns a boolean value, you’ll get the error:

# 🚫 Raises TypeError: 'bool' object is not callable
bool()()

Enter fullscreen mode

Exit fullscreen mode

In the above example, bool() returns False, and having an extra pair of parenthesis is like False().

How to fix TypeError: ‘bool’ object is not callable?

First, inspect the respective function’s value, and figure out how it ended up being a boolean object in the first place.

Sometimes figuring this out might be tricky. Below are three scenarios that lead to the «TypeError: ‘bool’ object is not callable» error:

  1. Declaring variable with a name that’s also the name of a function
  2. Calling a method that’s also the name of a property
  3. Calling a method decorated with @property

Let’s explore each scenario with some examples.

Declaring a variable with a name that’s also the name of a function: A Python function is an object like any other built-in object, such as int, float, dict, list, etc.

All built-in functions are defined in the builtins module and assigned a global name for easier access. For instance, str() is __builtins__.str().

That said, overriding a function (accidentally or on purpose) with another value is technically possible.

For instance, if you define a variable named str and initialize it with a boolean value, it’ll no longer point to the str class.

# ⚠️ the value of the built-in function str() is changed to True
str = True
score = 15

# 🚫 Raises TypeError
print ('The score is: ' + str(score))

Enter fullscreen mode

Exit fullscreen mode

If you run the above code, Python will complain with a «TypeError: ‘bool’ object is not callable» error because True (the new value of str) isn’t callable.

You have two ways to fix the issue:

  • Rename the variable str
  • Explicitly access the str function from the builtins module (__bultins__.str)

The second approach isn’t recommended unless you’re developing a module. For instance, if you want to implement an open() function that wraps the built-in open():

# Custom open() function using the built-in open() internally
def open(filename):
     # ...
     __builtins__.open(filename, 'w', opener=opener)
     # ...

Enter fullscreen mode

Exit fullscreen mode

In almost every other case, you should always avoid naming your variables as existing functions and methods. But if you’ve done so, renaming the variable would solve the issue.

So the above example could be fixed like this:

status = True
score = 15

print ('The score is: ' + str(score))
# Output: The score is: 15

Enter fullscreen mode

Exit fullscreen mode

⚠️ Long story short, you should never use a function name (built-in or user-defined) for your variables!

Overriding functions (and calling them later on) is one of the most common causes of the «TypeError: ‘bool’ object is not callable» error. It’s similar to calling integer numbers.

Now, let’s get to the less common mistakes that lead to this error.

Calling a method that’s also the name of a property: When you define a property in a class constructor, it’ll shadow any other attribute of the same name.

class Book:
    def __init__(self, title, published):
        self.title = title
        self.published = published

    def published(self):
        return self.published


book = Book('Learning Python', True)

# 🚫 Raises TypeError: 'bool' object is not callable
if book.published():
    print('The book is published.')

Enter fullscreen mode

Exit fullscreen mode

In the above code, class Book contains a property named published that defines whether the books is published or not. Further down, we defined a method, also named published.

As a result, any reference to published returns the property not the method. And if you try to call this property, you should expect the «TypeError: ‘bool’ object is not callable» error.

The method name is_published sounds like a safer and more readable alternative:

class Book:
    def __init__(self, title, published):
        self.title = title
        self.published = published

    def is_published(self):
        return self.published


book = Book('Learning Python', True)

if book.is_published():
    print('The book is published.')
# Output: The book is published.

Enter fullscreen mode

Exit fullscreen mode

Calling a method decorated with @property decorator: The @property decorator turns a method into a “getter” for a read-only attribute of the same name.

class User:
    def __init__(self, user_id, active):
        self._user_id = user_id
        self._active = active

    @property
    def active(self):
        return self._active


user = User(1, True)

# 🚫 Raises TypeError: 'bool' object is not callable
if user.active():
    print('User is active!')

Enter fullscreen mode

Exit fullscreen mode

You need to access the getter method without the parentheses:

class User:
    def __init__(self, user_id, active):
        self._user_id = user_id
        self._active = active

    @property
    def active(self):
        return self._active


user = User(1, True)

if user.active:
    print('User is active!')

# Output: User is active!

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

Alright, I think it does it! I hope this quick guide helped you fix your problem.

Thanks for reading.

❤️ You might like:

  • TypeError: ‘tuple’ object is not callable in Python
  • TypeError: ‘dict’ object is not callable in Python
  • TypeError: ‘list’ object is not callable in Python
  • TypeError: ‘str’ object is not callable in Python
  • TypeError: ‘float’ object is not callable» in Python
  • TypeError: ‘int’ object is not callable in Python

TypeError: ‘bool’ object is not callable in Python; it could be that you are naming the function the same as the variable that contains the data type, or maybe you are overriding the bool() function to a primitive function containing the boolean data type then calling it out. Follow this article to understand better.

The reason is that bool objects do not respond to function calls because they are not functions.

Example: 

def checkEvenNumber(num):
  if (num % 2) == 0:
    return True
  else:
    return False  

checkEvenNumber = True
checkEvenNumber = checkEvenNumber(3) # TypeError: 'bool' object is not callable
print(checkEvenNumber)

Output:

TypeError: 'bool' object is not callable

The cause of the error was that I declared a variable named with the function we want to call: checkEvenNumber = checkEvenNumber(3)

How to solve this error?

The difference in variable and function naming

To fix this, you need to be careful not to name the function the same as the variable name containing the boolean data type.

Example:

  • Use a different variable name than the function name.
  • I replaced the variable name ‘isEvenNumber’ in the wrong statement checkEvenNumber = checkEvenNumber(3) to isEvenNumber = checkEvenNumber(3).
def checkEvenNumber(num):
  if (num % 2) == 0:
    return True
  else:
    return False  

isEvenNumber = True
isEvenNumber = checkEvenNumber(3)
print(isEvenNumber)

Output:

False

Overriding built-in functions in Python

Example:

bool = False
print(bool('learnshareit'))

Output:

Traceback (most recent call last):
  File "code.py", line 2, in <module>
    print(bool('learnshareit'))
TypeError: 'bool' object is not callable

In this case, the mistake that caused the error was to override the list() function to a primitive function containing the boolean data type and then call it.

To fix the error in the above value, you need to change the variable that contains a boolean data type that is not the name of a built-in function in Python.

Example:

# Change the variable name. Avoid naming variables as built-in functions in Python
boolObj = False
print(bool('learnshareit'))

Output:

True

Checking if an object is callable

This is not a fix but a way for you to check if an object is callable to avoid mishaps while you code. I will use the callable() function.

Syntax:

callable(object)

Parameters:

  • object: object to be tested.

The callable() function checks if the objects are callable or not. If the object is allowed to be called, the function returns True. Otherwise, it returns False.

Example:

bool = False
print(callable(bool))

Output:

False

In the above example, the callable() function returns False, which ensures that the bool object is not callable.

Summary

I hope you enjoy our article about the TypeError: ‘bool’ object is not callable in Python. If you have any questions about this issue, please leave a comment below. We will answer your questions as possible. Thanks!

Maybe you are interested:

  • SyntaxError: non-default argument follows default argument
  • TypeError: ‘tuple’ object does not support item assignment
  • TypeError: can only concatenate str (not “list”) to str

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

The TypeError: 'bool' object is not callable error occurs when you try to call a Boolean value (True or False) as a function. In Python, the bool type is used to represent the truth values of a condition, and when you try to call it as a function, it results in the above mentioned error. The error message indicates that a boolean object is being treated as if it were a function, and is therefore not callable. In this article, we will go through several methods to resolve this error in your Python code.

Method 1: Check for reserved words

To fix the TypeError: 'bool' object is not callable error in Python, you can check if you are using any reserved words as function or variable names. Reserved words are words that are used by Python for specific purposes and cannot be used as function or variable names.

Here is an example code snippet that demonstrates how using a reserved word as a function name can lead to the TypeError: 'bool' object is not callable error:

def True():
    print("Hello, world!")

True()

In this example, we have defined a function named True, which is a reserved word in Python. When we try to call the True() function, we get the TypeError: 'bool' object is not callable error because Python is trying to call the built-in True boolean value as a function.

To fix this error, we need to rename our function to something that is not a reserved word. Here is the corrected code:

def my_function():
    print("Hello, world!")

my_function()

In this example, we have renamed our function to my_function, which is not a reserved word in Python. Now when we call the my_function() function, it will execute without any errors.

In summary, to fix the TypeError: 'bool' object is not callable error in Python, you should check if you are using any reserved words as function or variable names. If you are, rename them to something that is not a reserved word.

Method 2: Check for overlapping names

This error occurs when you try to call a boolean value as a function. To fix this error, you can use the «Check for Overlapping Names» method, which involves checking if any of your variable names are the same as built-in Python functions or keywords.

Here is an example code that demonstrates this method:

def my_function():
    if (True):
        print("True")
    else:
        print("False")

def my_function():
    if (bool):
        print("True")
    else:
        print("False")

In the first example, the function uses True as a boolean value, but it is also a built-in Python function. In the second example, we replace True with the bool keyword to avoid the error.

Here is another example that demonstrates how to use this method with variables:

def my_function():
    x = True
    if (x()):
        print("True")
    else:
        print("False")

def my_function():
    x = True
    if (bool(x)):
        print("True")
    else:
        print("False")

In the first example, the variable x is set to True, but it is called as a function, causing the error. In the second example, we use the bool keyword to check the value of x instead.

In summary, to fix the «TypeError: ‘bool’ object is not callable» error in Python using the «Check for Overlapping Names» method, you should check if any of your variable names are the same as built-in Python functions or keywords, and replace them if necessary.

Method 3: Check for lambda function

When you encounter the error message «TypeError: ‘bool’ object is not callable» in Python, it means that you are trying to call a Boolean object as if it were a function. This can happen if you accidentally assign a Boolean value to a variable that was previously a function. One way to fix this issue is to check if the variable is a lambda function before calling it.

def my_function():
    return True

my_variable = my_function()
if my_variable():
    print("Hello, world!")

def my_function():
    return True

my_variable = my_function()
if hasattr(my_variable, '__call__') and isinstance(my_variable, type(lambda: None)):
    my_variable()
    print("Hello, world!")

In the fixed code, we first check if the variable my_variable has the attribute __call__, which indicates that it is callable. We also check if it is an instance of a lambda function, which is a type of function that is defined inline. If both of these conditions are true, we can safely call the variable as if it were a function.

Another example of using the lambda function check:

my_variable = True
if my_variable():
    print("Hello, world!")

my_variable = True
if hasattr(my_variable, '__call__') and isinstance(my_variable, type(lambda: None)):
    my_variable()
    print("Hello, world!")

In this example, we assign the Boolean value True to the variable my_variable, which causes the error when we try to call it as if it were a function. By using the lambda function check, we can avoid this error and safely call the variable if it is a lambda function.

In summary, to fix the «TypeError: ‘bool’ object is not callable» error in Python, you can check if the variable is a lambda function before calling it. This can be done using the hasattr function to check for the __call__ attribute and the isinstance function to check if the variable is a lambda function.

Method 4: Check for string representation of boolean value

One way to fix the TypeError: 'bool' object is not callable error is to check for the string representation of the boolean value. Here’s how you can do it in Python:

is_true = True

if str(is_true).lower() == 'true':
    print('The boolean variable is True')
else:
    print('The boolean variable is False')

In this example, we define a boolean variable is_true and check if its string representation is equal to the string 'true'. We use the str() function to convert the boolean value to a string, and the lower() method to convert the string to lowercase before comparing it to the string 'true'.

Here’s another example that shows how you can use a function to check the boolean value:

def is_true(value):
    return str(value).lower() == 'true'

is_true_var = True

if is_true(is_true_var):
    print('The boolean variable is True')
else:
    print('The boolean variable is False')

In this example, we define a function is_true() that takes a value as its argument and returns True if the string representation of the value is equal to 'true'. We then define a boolean variable is_true_var and call the function to check its value.

Overall, checking the string representation of boolean values is a simple and effective way to avoid the TypeError: 'bool' object is not callable error in Python.

redded123

-36 / 0 / 0

Регистрация: 13.03.2020

Сообщений: 101

1

23.07.2021, 12:02. Показов 8868. Ответов 14

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Добрый день, не могу понять в чём ошибка, помогите плиз

Python
1
2
3
4
5
button1=Button(win, width=15,height=1, text='Купить', bg=color1, command=lambda:[check1(True),buy()])
    button1.place(x=56,y=356)
    i1 = Image.open('fons/game_fon/fon1.png')
    p1 = ImageTk.PhotoImage(i1)
    i1 = canvas.create_image(18, 162, anchor='nw',image=p1)

Данная часть кода находится в функции, переменная check1 глобальная, в не функции эту переменную уже определил, не понимаю почему питон ругается на строчке с if check1==True???



0



1007 / 351 / 59

Регистрация: 28.02.2013

Сообщений: 931

23.07.2021, 12:19

2

redded123, лучше приведите минимально рабочий пример, что бы скопировал, вставил, запустил и получил ошибку)
Потому что ваш код не информативен. Например:
1. где строчка «if check1==True»?
2. где в коде переменная check1?
3. «в не функции эту переменную уже определил» — где это место в коде?

И тому подобное.



2



Автоматизируй это!

Эксперт Python

7345 / 4525 / 1200

Регистрация: 30.03.2015

Сообщений: 13,084

Записей в блоге: 29

23.07.2021, 12:35

3

Цитата
Сообщение от redded123
Посмотреть сообщение

check1(True)

чек1 это функция или булин? а то ниже ты пишешь

Цитата
Сообщение от redded123
Посмотреть сообщение

if check1==True



0



-36 / 0 / 0

Регистрация: 13.03.2020

Сообщений: 101

24.07.2021, 12:02

 [ТС]

4

Welemir1, check1 я в начале кода определил как False, а после нажатия на кнопку я хотел бы, чтобы check1 стал True. Это все надо, чтобы проверить какая именно кнопка нажата, если коротко отвечать на ваш вопрос, то check1-булин



0



Автоматизируй это!

Эксперт Python

7345 / 4525 / 1200

Регистрация: 30.03.2015

Сообщений: 13,084

Записей в блоге: 29

24.07.2021, 12:08

5

redded123, ты не прочел что я написал?

вот как ты используешь переменную:

Цитата
Сообщение от redded123
Посмотреть сообщение

check1(True)

Цитата
Сообщение от redded123
Посмотреть сообщение

if check1==True

так это функция или нет? если нет то нафиг ты пишешь check1(True) ?



0



-36 / 0 / 0

Регистрация: 13.03.2020

Сообщений: 101

24.07.2021, 12:35

 [ТС]

6

Welemir1, а как тогда передать переменной check1 значение True через команду в кнопке?



0



Автоматизируй это!

Эксперт Python

7345 / 4525 / 1200

Регистрация: 30.03.2015

Сообщений: 13,084

Записей в блоге: 29

24.07.2021, 14:13

7

redded123, ну как минимум погуглить, почитать документацию ткинтера, посмотреть примеры. У тебя же огрызок кода, не понятно зачем и куда ты передаешь.



1



Эксперт Python

5412 / 3836 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

24.07.2021, 18:55

8

Цитата
Сообщение от redded123
Посмотреть сообщение

переменной check1 значение True через команду в кнопке?

Написать функцию, которая изменит значение нужной тебе переменной.
command принимает только функции.

Цитата
Сообщение от redded123
Посмотреть сообщение

переменная check1 глобальная,

Первое что тебе нужно удалить из кода. В коде не должно быть глобальных переменных, которые ты изменяешь.

P.S. Уже можно пробовать читать документацию по Python. Сам видишь — у тебя ничего не получается наобум.



0



-36 / 0 / 0

Регистрация: 13.03.2020

Сообщений: 101

26.07.2021, 09:31

 [ТС]

9

Хорошо, задам вопрос по другому. Как по нажатию на кнопку понять какая именно кнопка нажата
P.S у меня кучу кнопок, поэтому для каждой кнопки создавать свою функцию это просто бред, получится более 1000 строк кода



0



kapbepucm

1425 / 670 / 299

Регистрация: 02.05.2020

Сообщений: 1,534

26.07.2021, 10:54

10

Лучший ответ Сообщение было отмечено redded123 как решение

Решение

Цитата
Сообщение от redded123
Посмотреть сообщение

в начале кода определил как False, а после нажатия на кнопку я хотел бы, чтобы check1 стал True

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from tkinter import *
win = Tk()
win.geometry("500x500")
 
def buy(p):
  global check1
  check1 = p
  print(check1)
 
check1 = False
button1=Button(win, width=15,height=1, text='Купить', command=lambda p=True: buy(p))
button1.place(x=56,y=356)
 
win.mainloop()

Но, как тут уже писали, так лучше не делать.

Чтобы просто кнопки различать, можно использовать чтото похожее:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
from tkinter import *
win = Tk()
 
def buy(b):
  print("нажата кнопка " + str(b))
 
button1=Button(win, text='Купить', command=lambda b=1: buy(b))
button1.pack()
 
button2=Button(win, text='Купить', command=lambda b=2: buy(b))
button2.pack()
 
win.mainloop()



2



Эксперт Python

5412 / 3836 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

27.07.2021, 13:59

11

Цитата
Сообщение от redded123
Посмотреть сообщение

для каждой кнопки создавать свою функцию это просто бред,

Ты странный. А как по твоему люди делают?
Если нужна функция — пишут функцию. Если функция маленькая — используют анонимную лямбду созданную inpalce (это тоже функция).
1000 строчек это еще очень маленькая программка. С учетом гуиговнокодинга.
Посмотри на свой код внимательно — там есть примерно 30% кода, который можно просто удалить и еще 30%, который можно переписать более компактно.



0



redded123

-36 / 0 / 0

Регистрация: 13.03.2020

Сообщений: 101

30.07.2021, 12:37

 [ТС]

12

Garry Galler, ооо ты такой профессиАНАЛ, так покажи как можно 30% кода убрать и еще 30%, который можно переписать более компактно, вот в этом коде

Python
1
2
3
4
5
button1=Button(win, width=15,height=1, text='Купить', bg=color1, command=lambda:[check1(True),buy()])
button1.place(x=56,y=356)
i1 = Image.open('fons/game_fon/fon1.png')
p1 = ImageTk.PhotoImage(i1)
i1 = canvas.create_image(18, 162, anchor='nw',image=p1)



0



Модератор

Эксперт Python

1354 / 651 / 207

Регистрация: 23.03.2014

Сообщений: 3,057

30.07.2021, 12:59

13

Цитата
Сообщение от Garry Galler
Посмотреть сообщение

для каждой кнопки создавать свою функцию это просто бред,

Delphi с Pascal на Вас нет)))



0



Эксперт Python

5412 / 3836 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

30.07.2021, 14:50

14

Цитата
Сообщение от redded123
Посмотреть сообщение

Как по нажатию на кнопку понять какая именно кнопка нажата

Ошибка: 'bool' object is not callable

Цитата
Сообщение от redded123
Посмотреть сообщение

еще 30%, который можно переписать более компактно,

Вот простой пример. Ты бы написал 24 кнопки подряд.



1



Эксперт Python

5412 / 3836 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

30.07.2021, 14:55

15

del



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

30.07.2021, 14:55

15

Понравилась статья? Поделить с друзьями:
  • Bookworm 5b7c4439 far cry 5 ошибка
  • Bookmate windows ошибка соединения
  • Bonfiglioli ошибка f1205
  • Booking ошибка при бронировании
  • Bonjour warcraft 3 ошибка