Search code examples
pythonpython-3.xtkintertkinter-entrytkinter-menu

How to return an output directly without creating a button in Tkinter


Good evening, I am struggling to return an output without creating a button in Tkinker. I want to return either "Excellent" or "Done" based on the input but only the input is showing.

Below is the code I'm struggling with

from tkinter import *

root = Tk()

num = StringVar()
entry1 = Entry(root, textvariable=num).pack()

remark = StringVar()
entry2 = Entry(root, textvariable=remark).pack()

def set_label(name, index, mode):
    return remark.set(num.get())
    if result > 56:
        return "Excellent"
    else:
        return "Done"

num.trace('w', set_label)
num.set('')

root.mainloop

Solution

  • I was not exactly sure what you wanted to do, but I modified your function to determine if num entry is ''. If not then convert value fetched to int and compare to 56. If larger, then insert entry "Excellent" in remark entry, otherwise put "Done" in remark entry.

    As you enter each digit, the comparison to 56 will take place so the first digit will always result in "Done" appearing. Once you exceed 56 (which will require a minimum of 2 digits) it will continue to remain "Excellent".

    Again, I did the best I could with the logic provided. Here's the full code:

    from tkinter import *
    
    root = Tk()
    
    num = StringVar()
    entry1 = Entry(root, textvariable=num).pack()
    
    remark = StringVar()
    entry2 = Entry(root, textvariable=remark).pack()
    
    def set_label(name, index, mode):
        result = num.get()
        if result == '':
            pass # not sure what rule should be here
        else:
            result = int(result)
            if result > 56:
                remark.set("Excellent")
            else:
                remark.set("Done")
    
    num.trace('w', set_label)
    num.set('')
    
    root.mainloop