Python Forum
GUI problems - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: GUI problems (/thread-23593.html)



GUI problems - Krisve94 - Jan-07-2020

Hi, I have searched for this problem for a while now, and I cannot find an answer anywhere.
I am creating a GUI for personal use playing DnD just to learn how to code. It is very fun and I have learned much in just a few weeks.
To calculate the score in a given attribute I use this formula: ("users input" - 10) / 2. Which means if you put in 20 the result shows 5.
Currently I am using a function to do this calculation, but to update it I have to use a button that runs the function again.
I found this bit of code and if I manage to modify it slightly it will make my GUI a lot simpler.


from tkinter import *
import math

root = Tk()

var = IntVar()
var.set(0)
user_input = Entry(root, textvariable=var)
user_input.pack()
result = Label(root, textvariable=var)

result.pack()
root.mainloop()
What is great about this is that the result label will duplicate the users input immediately without the need for running a function to either update of reprint a label. But I wish for the result label to do the calculation but everything I do ends up making the label be blank. There are no error messages, just an empty label. What I am trying to do i something like this;

from tkinter import *
import math

root = Tk()

var = IntVar()
var.set(0)
user_input = Entry(root, textvariable=var)
user_input.pack()
result = Label(root, textvariable=(var.get() - 10) / 2)

result.pack()
root.mainloop()
I have tried creating a new variable that does the calculation but it ends up with an empty label; (calculate = var.get() - 10) / 2

Is this possible or have I tried doing something that just not possible?


RE: GUI problems - Axel_Erfurt - Jan-07-2020

you should bind the return key to a function

something like this

from tkinter import *
import math
 
root = Tk()

def get_result(*args):
    r = (var.get() - 10) / 2
    result['text'] = r
    
r = ""
var = IntVar()
var.set(0)
user_input = Entry(root, textvariable=var)
user_input.bind('<Return>', get_result) 
user_input.pack()

result = Label(root, textvariable="")
result.pack()
root.mainloop()



RE: GUI problems - Krisve94 - Jan-07-2020

Thank you, it works perfectly Smile