Home > Back-end >  Use Scales values from tkinter to make calculations
Use Scales values from tkinter to make calculations

Time:05-02

I'm currently making kind of a configuration screen for a minesweeper, and I'd like the player to be able to choose how many row, columns and bombs are in the grid.
I already have all the logic behind, I'm currently implementing the GUI and I have trouble with the configuration screen:
I currently have this: Current gui.

And here's the code portion involved:

def __choice_screen(self):
    """Allows the user to configure the game settings"""
    self.master.title("Configuration")
    self.pack(fill=tk.BOTH, expand=1)

    self.canvas = tk.Canvas(self, width=400, height=200)
    self.canvas.pack(fill=tk.BOTH, side=tk.TOP)

    # Choosing rows and col
    lig = tk.IntVar()
    lig.set(8)

    self.lig_scale = tk.Scale(self, from_=5, to=20, orient=tk.HORIZONTAL, variable=lig)
    self.lig_scale.pack(side=tk.BOTTOM)

    col = tk.IntVar()
    col.set(8)
    self.col_scale = tk.Scale(self, from_=5, to=20, orient=tk.HORIZONTAL, variable=col)
    self.col_scale.pack(side=tk.BOTTOM)

    # Choosing number of bombs
    self.nb_bombes = tk.Spinbox(self, from_=1, to=(lig.get() * col.get()), wrap=True, width=4)
    self.nb_bombes.pack(side=tk.TOP)

    # DEBUG: 
    self.debug = tk.Label(self, text=f"DEBUG: {lig.get() * col.get()}")
    self.debug.pack(side="top", fill="x")

    self.master.mainloop()

I would like the maximal value of the Spinbox to be dynamically changed as (rows * columns) (i.e the number of cells in the grid), but it's not working (it's stuck to 64, which is the default values multiplied).

I've searched but didn't find a solution (I tried to link variables to the scales but it doesn't work as you can see), so thanks if someone can help :)

(Sorry for my english I'm french =D)

CodePudding user response:

The reason is When you use Label the text in it get stored once you create it. So to be able to change it, you have 2 approches:

  1. To change the text of label.
  • This isn't a recommed approcesh but would work.
  • for this, you will need a button to change the text.
  • this would also need you to update the screen or at least the widget.
def a():
    debug.config(text= f"Debug: {lig.get() * col.get()}")
    root.update() # can also be debug.update()
  1. Using text variable in label.
  • this is the most recommed approch.
result_var=StringVar()
def a():
    result=lig.get()* col.get()
    resultvar.set(result)
tk.Button(text='submit',command=a).pack()
debug(textvariable=result_var).pack()

I have used a button to execute the function, if don't want to use button check out this or use command parameter in both scales to execute code at changes as stated by @jasonharper.

Refrences:

  1. StringVar guide
  2. Difference Between Variable And Textvariable in tkinter
  • Related