Search code examples
pythontkinteropenpyxlf-stringdata-management

Unsure how to manage my variables/data using tkinter and openpyxl: fstring issue


I am creating an app on a Raspberry Pi (if its at all relevent) which needs to access data from specific cells from a spreadsheet in order to display the settings as button text. There are multiple 'modes', settings and buttons. The button that may need to update varies and I have specified this with a Boolean variable. The text that needs to be displayed on the specified button can also vary by time and worksheet. I was able to create a variable to hold the time and then using a nested f-string was able to display data from the correct cell:

current_time = datetime.now().strftime('%H')
cell_number = int(current_time)+2
bool = True

def update_button():
    if bool == True:
        button.config(text=f"{ws_sheet[f'A{cell_number}'].value}")
    else:
        button1.config(text=f"{ws_sheet[f'B{cell_number}'].value}")

This worked fine but I also need to alter the sheet now as well based on a different variable. I tried this but it produces an fstring syntax error.

current_time = datetime.now().strftime('%H')
cell_number = int(current_time)+2
bool = True
worksheet = some_worksheet 

def update_button():
    if bool == True:
        button.config(text=f"{{worksheet}[f'A{cell_number}'].value}")
    else:
        button1.config(text=f"{{worksheet}[f'B{cell_number}'].value}")

The syntax error produced:

button.config(text=f"{{worksheet}[f'A{cell_number}'].value}")
                  ^
SyntaxError: f-string: single '}' is not allowed

This seems like a counter-intuitive error to me as well.

I am open to the fact I am probably going about this totally the wrong way and for my own ego I feel compelled to mention that I haven't been doing this very long. I know I could achieve what I want with a ton of if/else statements but I was hoping to do something a bit more elegant.

Any help is greatly appreciated.


Solution

  • You can pass work sheet when calling your function.

    def update_button(ws_sheet):
        if bool == True:
            button.config(text=f"{ws_sheet[f'A{cell_number}'].value}"
        else:
            button1.config(text=f"{ws_sheet[f'B{cell_number}'].value}"