0

I'm working on a Tamagotchi-like app in Python with Tkinter. I detect clicks on a canvas item and increment a "clicks" counter stored in a JSON-backed character object. When the clicks reach multiples of 10, I also increase the "food" count and want to update the button text or image to reflect the new food amount.

My click handler calls this increment method which updates the clicks and food values correctly in the JSON and in memory:

def increment_clicks(self):
    click_count = self.character.stats.get("clicks", 0)
    print(click_count)
    self.character.stats["clicks"] = click_count + 1
    if click_count % 10 == 0:
        self.character.stats["food"] = self.character.stats.get("food", 0) + 1
        self.ui.update_feed_button()

The method to update the button is:

def update_feed_button(self):
    food_count = self.character.stats.get("food", 0)
    if self.btn_feed:
        self.btn_feed.config(text=f"{food_count}")

And the button is defined like this:

self.btn_feed = tk.Button(
    self.root, text=f"{food_count}",
    font=("Arial", 10),
    image=self.food_photo_on,
    compound="center",
    bd=0,
    command=self.on_feed_tamago
)

here is the call from my game.py file:

if self.character.character_exists():
    self.ui.increment_clicks(self)

However, the button's text or image does not update after incrementing the food count. I suspect this is because the self references in the click handler and the button might be pointing to different instances or files, so the UI update doesn't reflect the changed value.

How can I properly update the button UI when the food count changes in this kind of multi-file Tkinter application?

I'm not an python expert just wanted to have fun if you need anything i can send more context

2
  • 3
    Please edit your question to provide a complete minimal reproducible example, that is, something we can run as-written without having to make any assumptions as to how your project is structured. Commented Jun 17 at 19:20
  • 1
    hard to say what is the problem when we can't run it. Maybe you created two buttons and now you update text in wrong button, or maybe food_count doesn't change. Or maybe self.character.character_exists() always give False. You would have to create minimal working code so we could simply copy and run it. At this moment you can only debug code on your own. You can even use print() to see which part of code is executed and what you have in variables. Commented Jun 18 at 13:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.