Chi
Chi

Reputation: 29

how could i update integer variable with tkinter?

i found a tutorial on google which integer value could be update by using .config(). So I had using the below code to update the value. I think my logic it wrong by put the while loop like that , but i not sure how could i update the a = a + 1 on to the gui.

My code :

import tkinter as tk
from random import randint

master_window = tk.Tk()
master_window.geometry("250x150")
master_window.title("IntVar Example")
lab = tk.Label(master_window)
integer_variable = tk.IntVar()
integer_variable.set(2)

label = tk.Label(master_window,text="output", height=50)
label.place(x=80, y=80)
a = 25 



def update():
   my_data=integer_variable.get(a) # read the value of selected radio button
   label.config(text=str(my_data)) # Update the Label with data



while True: 
   a = a + 1 
   master_window.update()  
   master_window.mainloop()





Upvotes: 0

Views: 655

Answers (2)

toyota Supra
toyota Supra

Reputation: 4595

how could i update integer variable with tkinter?

There are two(2) ways to do.

Either you want to start from 25 to upward or start from 1 to upward. It can be used the same script.

  • Add namespace partial.
  • Create increment_counter function.
  • Add IntVar() and assign variable
  • Add variable.set(25)

Snippet:

import tkinter as tk
from functools import partial


def increment_counter(var: int, amount: int) -> int:
   result = var.get()
   result += amount
   
   var.set(result)

 
root=tk.Tk()
variable = tk.IntVar()
variable.set(25)

tk.Button(root, width=10, text="Increase",
          command=partial(increment_counter, variable, +1),
          fg='red', bg="white").grid(column=0, row=0,
          padx=20, pady=(10,0))

tk.Label(root, width=5, height=2, textvariable=variable,
         bg="white", font="Verdana 16 bold").grid(column=0,
         row=1,padx=20, pady=10)
    

root.mainloop()

Screenshot:

enter image description here

Upvotes: 0

npetrov937
npetrov937

Reputation: 168

The setup you have so far is quite strange and your intuition that the logic is wrong is accurate.

Here's an alternative to get you started - note how I refrain from using external variables and instead use the .set() and get() operations to change the value of the integer_variable:

import tkinter as tk

master_window = tk.Tk()
master_window.geometry("250x150")
master_window.title("IntVar Example")

integer_variable = tk.IntVar()
integer_variable.set(2)

label = tk.Label(master_window, text=integer_variable.get())
label.grid(row=0, column=0)
button = tk.Button(master_window, text="Update value", command=update)
button.grid(row=1, column=0)

def update():
    curr_integer_variable_value = integer_variable.get()
    updated_integer_value = curr_integer_variable_value + 1
    integer_variable.set(updated_integer_value)
    label.config(text=str(integer_variable.get()))

master_window.mainloop()

Upvotes: 1

Related Questions