Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 GUI problems
#1
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?
Quote
#2
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()
Quote
#3
Thank you, it works perfectly Smile
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)