Tkinter Search Box with Editable Output?

  Kiến thức lập trình

I am using the following TKinter Code to return a matching value from an existing dictionary.
However, in my usecase the returned value is not always going to be accurate, just a good guess based on past data. So I will need to be able to edit the second field after the ‘guess’.

If I remove output_entry.delete(0, END) upon keypress, values just accumulate with both the Entry and the Result. As an example: If I type “A” in the Entry field, “1” returns as a result. If I try to type “B” in The Result field, I will get “A1B2” because the keypress is still calculating guesses.

How can I modify this so that the second field will return a search of the dictionary by the first field, but remain editable upon click of the second field?

Thank you!

import tkinter as tk
from tkinter import *
import json

Lookup =  { "A": "1", "B": "2", "C": "3" }

app = Tk()
app.geometry("400x350")

input_var = tk.StringVar()
Label(app, text="Letter: ", padx=3, pady=3).grid(column=0, row=0)
input_entry = tk.Entry(width=15, textvariable=input_var)
input_entry.grid(column=1, row=0, padx=20, pady=20)

result_var = tk.StringVar()
Label(app, text="Number: ", padx=3, pady=3).grid(column=0, row=20)
output_entry = tk.Entry(app, width=15, textvariable=result_var)
output_entry.grid(column=1, row=20)

def key_pressed(name, index, mode):
    output_entry.delete(0, END)
    try:
        output_entry.insert(0, Lookup[input_entry.get()])
    except Exception:
        output_entry.insert(0, "")

output_entry.delete(0, END)
input_entry.delete(0, END) 
input_var.trace("w", key_pressed)
result_var.trace("w", key_pressed)

app.mainloop()

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT