Skip to content
Advertisement

Tkinter: keep update a variable

I really need help, my brain is melting because of this problem. I’ve studied python for 2 months maybe and I’m not very expert in programming. I’ve got an issue… I’m using tkinter on this program; in this small GUI I’d like to always keep updated the global variable “temp”, and its value should change everytime I click on the button. I know that mainloop() is a blocking method, so it is possible to do something like this?

import tkinter as tk


class App:
def __init__(self):
    super().__init__()
    self.screen = tk.Tk()
    self.screen.geometry("400x400")
    self.screen.title("Modifica temperatura ambiente")
    self.screen.grid_columnconfigure(0, weight = 1)

    self.label = tk.Label(self.screen, text="ENTER TEMPERATUR VALUE", fg = "black", font = ("Calibri", 10) )
    self.label.grid(row = 0, column = 0, sticky = "N", pady = 10)

    self.input_ = tk.Entry(self.screen)
    self.input_.grid(row = 1, column = 0, sticky = "WE", pady = 5, padx = 20)

    self.button = tk.Button(self.screen, text = "INVIA", command = self.getvalue)
    self.button.grid(row = 2, column = 0, sticky = "WE", pady = 5, padx = 10)

def getvalue(self):
    self.temp = self.input_.get()
    temperatura_label = tk.Label(self.screen, text = "Last input value is " + self.temp + " degrees", fg = "red")
    temperatura_label.grid(row = 3, column = 0, sticky = "S")
    return self.temp

app = App()
temp = app.getvalue()
print(temp)
app.screen.mainloop()

Thank for the help!

Advertisement

Answer

If you want to print it in the terminal, modify your getvalue function.

Code:

import tkinter as tk

screen = tk.Tk()
screen.geometry("400x400")
screen.title("Modifica temperatura ambiente")
screen.grid_columnconfigure(0, weight = 1)

class App:
    def __init__(self, master):
        super().__init__()
        self.master = master
        self.label = tk.Label(master, text="ENTER TEMPERATUR VALUE", fg = "black", font = ("Calibri", 10) )
        self.label.grid(row = 0, column = 0, sticky = "N", pady = 10)

        self.input_ = tk.Entry(master)
        self.input_.grid(row = 1, column = 0, sticky = "WE", pady = 5, padx = 20)


    def getvalue(self):
        self.temp = self.input_.get()
        temperatura_label = tk.Label(self.master, text = "Last input value is " + self.temp + " degrees", fg = "red")
        temperatura_label.grid(row = 3, column = 0, sticky = "S")
        if self.temp == None:
            print()
        else:
            return self.temp

app = App(screen)

def main_loop():
    global app
    temp = app.getvalue()
    print(temp)


button = tk.Button(screen, text = "INVIA", command = main_loop)
button.grid(row = 2, column = 0, sticky = "WE", pady = 5, padx = 10)



screen.mainloop()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement