#๐Ÿ”’ Making a mac os calculator

52 messages ยท Page 1 of 1 (latest)

mortal sparrowBOT
#

@worn venture

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

worn venture
#

why is it getting deleted

#

Hello Im making a mac os calculator in tkinter and i cant figure out where to add background colors for the buttons

torn shard
#

!code

mortal sparrowBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

worn venture
torn shard
#

Are you trying to upload a file? Use a code block or the pastebin instead

worn venture
#

class CalculatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Calculator")

        # Entry widget to display the result
        self.result_var = tk.StringVar()
        self.result_var.set("0")

        self.result_entry = tk.Entry(root, textvariable=self.result_var, font=('Helvetica', 36), bd=1, insertwidth=4, width=20, justify='right', bg='gray17')
        self.result_entry.grid(row=0, column=0, columnspan=4)

        # Buttons layout
        buttons = [
            ('C', 'DarkOrange1'), ('+/-', 'darkorange1'), ('%', 'darkorange1'), ('/', 'darkorange1'),
            ('7', '#d4d4d2'), ('8', '#d4d4d2'), ('9', '#d4d4d2'), ('*', 'darkorange1'),
            ('4', '#d4d4d2'), ('5', '#d4d4d2'), ('6', '#d4d4d2'), ('-', 'darkorange1'),
            ('1', '#d4d4d2'), ('2', '#d4d4d2'), ('3', '#d4d4d2'), ('+', 'darkorange1'),
            ('0', '#d4d4d2'), ('.', '#d4d4d2'), ('=', 'darkorange1')
        ]
mortal sparrowBOT
#

Hey @worn venture!

It looks like you pasted Python code without syntax highlighting.

Please use syntax highlighting to improve the legibility of your code and make it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
worn venture
#
import tkinter as tk

class CalculatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Calculator")

        # Entry widget to display the result
        self.result_var = tk.StringVar()
        self.result_var.set("0")

        self.result_entry = tk.Entry(root, textvariable=self.result_var, font=('Helvetica', 36), bd=1, insertwidth=4, width=20, justify='right', bg='gray17')
        self.result_entry.grid(row=0, column=0, columnspan=4)

        # Buttons layout
        buttons = [
            ('C', 'DarkOrange1'), ('+/-', 'darkorange1'), ('%', 'darkorange1'), ('/', 'darkorange1'),
            ('7', '#d4d4d2'), ('8', '#d4d4d2'), ('9', '#d4d4d2'), ('*', 'darkorange1'),
            ('4', '#d4d4d2'), ('5', '#d4d4d2'), ('6', '#d4d4d2'), ('-', 'darkorange1'),
            ('1', '#d4d4d2'), ('2', '#d4d4d2'), ('3', '#d4d4d2'), ('+', 'darkorange1'),
            ('0', '#d4d4d2'), ('.', '#d4d4d2'), ('=', 'darkorange1')
        ]
#
 row_val = 1
        col_val = 0

        for button_text, button_color in buttons:
            btn = tk.Button(root, text=button_text, padx=20, pady=20, font=('Helvetica', 18), command=lambda b=button_text: self.on_button_click(b), bg='cyan')
            btn.grid(row=row_val, column=col_val, sticky="nsew")

            
            col_val += 1

            if col_val > 3:
                col_val = 0
                row_val += 1

            # Configure row and column weights for resizing
            root.grid_rowconfigure(row_val, weight=1)
            root.grid_columnconfigure(col_val, weight=1)

    def on_button_click(self, value):
        if value == '=':
            self.calculate_result()
        elif value == 'C':
            self.clear_result()
        elif value == '+/-':
            self.negate_result()
        elif value == '%':
            self.calculate_percentage()
        else:
            self.append_to_result(value)

    def append_to_result(self, value):
        current_result = self.result_var.get()
#
 # Check for consecutive operators
        if value in "+-*/" and current_result[-1] in "+-*/":
            return

        # Check for leading zero
        if current_result == "0":
            self.result_var.set(value)
        else:
            self.result_var.set(current_result + value)

    def clear_result(self):
        self.result_var.set("0")

    def negate_result(self):
        current_result = self.result_var.get()
        if current_result != "0":
            if current_result[0] == '-':
                self.result_var.set(current_result[1:])
            else:
                self.result_var.set('-' + current_result)
#
def calculate_percentage(self):
        current_result = self.result_var.get()
        try:
            result = str(float(current_result) / 100)
            self.result_var.set(result)
        except ValueError:
            self.result_var.set("Error")

    def calculate_result(self):
        current_result = self.result_var.get()
        try:
            result = str(eval(current_result))
            self.result_var.set(result)
        except ZeroDivisionError:
            self.result_var.set("Error")
        except Exception as e:
            self.result_var.set("Error")

if __name__ == "__main__":
    root = tk.Tk()
    app = CalculatorApp(root)
    root.mainloop()
worn venture
torn shard
#

Are all the buttons showing up as cyan blue?

worn venture
torn shard
#

Hmm I'm not sure, maybe get some screenshots to highlight whats wrong?

worn venture
torn shard
#

Sorry I meant of the UI

worn venture
#

i figured it would be somewhere along line 27 where i could insert like a (bg = 'DarkOrange1') or something but im not sure

#

oh sorry

torn shard
#

looks like that var is unused currently

worn venture
#

ok that what I thought do you know where I would be able to declare a color for that variable?

#

or where I should put it

torn shard
#

you already defined the text and color for each button in buttons

#

when you do for button_text, button_color in buttons then button_color is assigned each color from that list

worn venture
#

ah I see. So should I just delete the button_color variable all together

torn shard
#

From the loop? No you need to to use when creating each button

#

You should have something like ```py
for button_text, button_color in buttons:
btn = tk.Button(root, text=button_text, padx=20, pady=20, font=('Helvetica', 18), command=lambda b=button_text: self.on_button_click(b), bg=button_color)

#

Both the button_text and button_color variables are used to create each button

worn venture
#

ok I got it that makes sense. I guess im just still confused on how to change the individual button colors to make it look like this

#

do I have to declare button_color to be an actual tkinter color?

torn shard
#

It could be that your color codes are wrong? Are the gray button showing correctly?

#

I can't remember off the top of my head what strings tkinter accepts as colors

worn venture
#

this is my output im getting

#

Im not sure if the colors are wrong because ive tried mulitple different variations like the 'cyan' and none seem to work in changing the button colors

torn shard
#

actually you might have to use the tkmacosx library instead https://pypi.org/project/tkmacosx/

worn venture
#

omg youre right I cant believe i forgot to add that

torn shard
#

Lucky google search on my part turned up someone with a similar problem

#

you are using osx right?

worn venture
#

haha yes I am

#

perfect the colors are changing now thanks for all your help im still trying to get used to using discord for this kind of stuff

torn shard
#

nice!

#

yeah no problem, usually though if you have a lot of code to paste just use

#

!paste

mortal sparrowBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

torn shard
#

If it's short enough, use a codeblock

worn venture
#

awesome I will, thanks again

mortal sparrowBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.