1

I am working on creating a RPG status window for fun (like when you level up in a rpg and you add skill points to certain stats). I'm just trying to create the status window for now (showing the name of the player, the stats, and their class based on their stats, etc).

This is what I have so far:

from tkinter import *
from tkinter import ttk

root = Tk()
root.geometry("300x300")

counter = IntVar()

def increase_stat(event=None):
    counter.set(counter.get() + 1)
def decrease_stat(event=None):
    counter.set(counter.get() - 1)

rnum = 0

for stat in ["Str","Int","Dex"]:
    Label(root, text=stat).grid(row=rnum, column=0)
    Label(root, textvariable=counter).grid(row=rnum+1, column=1)
    Button(root, text="+", command=increase_stat).grid(row=rnum+1, column=0)
    Button(root, text="-", command=decrease_stat).grid(row=rnum+1, column=2)
    rnum = rnum + 2

root.mainloop()

This is the result of this code so far:

Result of this code

The problem I'm having is that pressing the "+" or "-" button of any stat affects every other stat instead of just the stat I'm clicking. For example, clicking the "+" button under "Str" to add +1 to "Str" instead adds +1 to all three stats.

I'm just starting this so I'll be adding more than just those three stats (like displaying what class a character is based on the stats) so any assistance will be appreciated.

1
  • 2
    Well, you have exactly one IntVar that you are increasing or decreasing, so how could it possibly work otherwise? You need a separate var per stat. Commented Aug 21, 2018 at 21:22

1 Answer 1

1

You need to create one variable to record the increments and decrements for each label; you also must indicate which counter must be altered.

Maybe something like this?

import tkinter as tk

root = tk.Tk()
root.geometry("300x300")

def increase_stat(event=None, counter=None):
    counter.set(counter.get() + 1)

def decrease_stat(event=None, counter=None):
    counter.set(counter.get() - 1)

counters = [tk.IntVar() for _ in range(3)]

rnum = 0
for idx, stat in enumerate(["Str", "Int", "Dex"]):
    tk.Label(root, text=stat).grid(row=rnum, column=0)
    tk.Label(root, textvariable=counters[idx]).grid(row=rnum+1, column=1)
    tk.Button(root, text="+", command=lambda counter=counters[idx]: increase_stat(counter=counter)).grid(row=rnum+1, column=0)
    tk.Button(root, text="-", command=lambda counter=counters[idx]: decrease_stat(counter=counter)).grid(row=rnum+1, column=2)
    rnum = rnum + 2

root.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

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.