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?
JavaScript
x
31
31
1
import tkinter as tk
2
3
4
class App:
5
def __init__(self):
6
super().__init__()
7
self.screen = tk.Tk()
8
self.screen.geometry("400x400")
9
self.screen.title("Modifica temperatura ambiente")
10
self.screen.grid_columnconfigure(0, weight = 1)
11
12
self.label = tk.Label(self.screen, text="ENTER TEMPERATUR VALUE", fg = "black", font = ("Calibri", 10) )
13
self.label.grid(row = 0, column = 0, sticky = "N", pady = 10)
14
15
self.input_ = tk.Entry(self.screen)
16
self.input_.grid(row = 1, column = 0, sticky = "WE", pady = 5, padx = 20)
17
18
self.button = tk.Button(self.screen, text = "INVIA", command = self.getvalue)
19
self.button.grid(row = 2, column = 0, sticky = "WE", pady = 5, padx = 10)
20
21
def getvalue(self):
22
self.temp = self.input_.get()
23
temperatura_label = tk.Label(self.screen, text = "Last input value is " + self.temp + " degrees", fg = "red")
24
temperatura_label.grid(row = 3, column = 0, sticky = "S")
25
return self.temp
26
27
app = App()
28
temp = app.getvalue()
29
print(temp)
30
app.screen.mainloop()
31
Thank for the help!
Advertisement
Answer
If you want to print it in the terminal, modify your getvalue
function.
Code:
JavaScript
1
42
42
1
import tkinter as tk
2
3
screen = tk.Tk()
4
screen.geometry("400x400")
5
screen.title("Modifica temperatura ambiente")
6
screen.grid_columnconfigure(0, weight = 1)
7
8
class App:
9
def __init__(self, master):
10
super().__init__()
11
self.master = master
12
self.label = tk.Label(master, text="ENTER TEMPERATUR VALUE", fg = "black", font = ("Calibri", 10) )
13
self.label.grid(row = 0, column = 0, sticky = "N", pady = 10)
14
15
self.input_ = tk.Entry(master)
16
self.input_.grid(row = 1, column = 0, sticky = "WE", pady = 5, padx = 20)
17
18
19
def getvalue(self):
20
self.temp = self.input_.get()
21
temperatura_label = tk.Label(self.master, text = "Last input value is " + self.temp + " degrees", fg = "red")
22
temperatura_label.grid(row = 3, column = 0, sticky = "S")
23
if self.temp == None:
24
print()
25
else:
26
return self.temp
27
28
app = App(screen)
29
30
def main_loop():
31
global app
32
temp = app.getvalue()
33
print(temp)
34
35
36
button = tk.Button(screen, text = "INVIA", command = main_loop)
37
button.grid(row = 2, column = 0, sticky = "WE", pady = 5, padx = 10)
38
39
40
41
screen.mainloop()
42