I am working on a project and I need to detect a change in the text box and change the text in another text box accordingly. Here is the function:
def work_change(event):
with open("uld.json", 'r', encoding="utf-8") as f:
data = json.load(f)
for i in range(len(data)):
if data[i]["code"] == int(e3.get("1.0", "end")) or data[i]["code1"] == int(e3.get("1.0", "end")):
description = data[i]["description"]
typeof = data[i]["type"]
print(description)
print(typeof)
e1.delete(1.0 ,"end")
e1.insert('end', description)
e2.delete(1.0 ,"end")
e2.insert('end', typeof)
break
I have tried everything and it just don't want to work. It detects the change but isn't changing the value in the text box. I don't know what to do and found no solution on web.
Here is my whole code:
import tkinter as tk
from tkinter import ttk, messagebox
import pandas as pd
import json
root = tk.Tk()
root.title("Polevar Generator")
root.geometry("800x500")
root.configure(background='#333')
labour_y = 50
labour_input = tk.Entry(root)
table_frame = None
canvas = None
container = None
# Function on data entry menu press
def data_entry():
global labour_input
global table_frame
global canvas
global container
if table_frame is not None:
table_frame.destroy()
if canvas is not None:
canvas.destroy()
if container is not None:
container.destroy()
labour_input.destroy()
labour_input = tk.Entry(root)
labour_input.place(x=30, y=20)
labour_input.delete(0, "end")
labour_input.insert(0, 'Enter Work Code')
labour_input.configure(state="disabled")
def labour_on_click(event):
labour_input.configure(state="normal")
labour_input.delete(0, "end")
global on_click_id
on_click_id = labour_input.bind('<Button-1>', labour_on_click)
def labour_submit(event):
global labour_code
labour_code = labour_input.get()
if labour_code != "Enter Work Code" and labour_code != "":
labour_input.delete(0, "end")
labour_input.insert(0, 'Enter Work Code')
labour_input.configure(state="disabled")
fetch_data(labour_code,0)
labour_input.bind('<Return>', labour_submit)
def fetch_data(code,factor):
description = ""
typeof = ""
with open("uld.json", 'r', encoding="utf-8") as f:
data = json.load(f)
for i in range(len(data)):
if data[i]["code"] == int(code) or data[i]["code1"] == int(code):
description = data[i]["description"]
typeof = data[i]["type"]
break
if description == "":
messagebox.showerror("Error", "Code not found.")
else: insert_labour(code,description,typeof)
def insert_labour(labour_code,description,typeof):
global labour_y
frame = tk.Frame(root)
frame.place(x=30, y=labour_y)
e1 = tk.Text(frame, width=20, height=4, fg="black", bg="#d1ffbd", font=('Arial', 10), wrap=tk.WORD)
e1.insert('end', description)
e1.configure(state="disabled")
e1.grid(row=0, column=1)
e2 = tk.Text(frame, width=5, height=4, fg="black", bg="#d1ffbd", font=('Arial', 10), wrap=tk.WORD)
e2.insert('end', typeof)
e2.configure(state="disabled")
e2.grid(row=0, column=2)
e3 = tk.Text(frame, width=5, height=4, fg="black", bg="#d1ffbd", font=('Arial', 10), wrap=tk.WORD)
e3.insert('end', labour_code)
e3.grid(row=0, column=3)
def work_change(event):
with open("uld.json", 'r', encoding="utf-8") as f:
data = json.load(f)
# Strip the newline character that Text widgets add automatically
code_input = e3.get("1.0", "end-1c").strip()
if not code_input: # Skip if empty
return
try:
code_input = int(code_input)
for i in range(len(data)):
if data[i]["code"] == code_input or data[i]["code1"] == code_input:
description = data[i]["description"]
typeof = data[i]["type"]
# Use string indices with quotes ("1.0" not 1.0)
e1.delete("1.0", "end")
e1.insert('end', description)
e2.delete("1.0", "end")
e2.insert('end', typeof)
break
except ValueError:
pass # Handle non-integer input
e3.bind("<KeyRelease>", work_change)
labour_y += 68
def display_csv_in_table():
global table_frame
global canvas
global container
if table_frame is not None:
table_frame.destroy()
if canvas is not None:
canvas.destroy()
if container is not None:
container.destroy()
df = pd.read_excel("uld.xlsx")
column_names = df.columns.tolist()
n_rows, n_cols = df.shape
container = tk.Frame(root, padx=20, pady=20)
container.pack(side="top", fill="both", expand=True)
canvas = tk.Canvas(container)
canvas.pack(side="left", fill="both", expand=True)
scroll_y = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scroll_y.pack(side="right", fill="y")
canvas.configure(yscrollcommand=scroll_y.set)
table_frame = tk.Frame(canvas)
canvas.create_window((0, 0), window=table_frame, anchor="nw")
col_widths = [5, 5, 50, 5 ,8, 15]
for j, col in enumerate(column_names):
if col =="nan":col=""
lbl = tk.Label(table_frame, text=col, width=col_widths[j % len(col_widths)], bg="lightgreen", relief="ridge", padx=5, wraplength=col_widths[j % len(col_widths)] * 10)
lbl.grid(row=0, column=j, sticky="nsew")
def load_rows():
for i in range(n_rows):
bg_color = "#f0f0f0" if i % 2 == 0 else "#ffffff"
for j in range(n_cols):
if str(df.iloc[i, j]) =="nan":df.iloc[i, j]=""
lbl = tk.Label(table_frame, text=str(df.iloc[i, j]), bg=bg_color, relief="ridge", padx=5, wraplength=col_widths[j % len(col_widths)] * 5, justify="left")
lbl.grid(row=i + 1, column=j, sticky="nsew", pady=2)
lbl.config(width=col_widths[j % len(col_widths)], justify="left")
table_frame.update_idletasks()
table_frame.grid_propagate(False)
canvas.config(scrollregion=canvas.bbox("all"))
print("Loaded")
def on_mousewheel(event):
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
canvas.bind_all("<MouseWheel>", on_mousewheel)
load_rows()
def uld():
display_csv_in_table()
def polevar():
global table_frame
global canvas
global labour_input
labour_input.destroy()
if table_frame is not None:
table_frame.destroy()
if canvas is not None:
canvas.destroy()
appbar = tk.Frame(root, bg="#444")
appbar.pack(fill='x', side="bottom")
uld_btn = tk.Button(appbar, text="ULD", bg="#444", fg="white", command=uld)
uld_btn.pack(padx=2, pady=2, side="left")
data_btn = tk.Button(appbar, text="Data Entry", bg="#444", fg="white", command=data_entry)
data_btn.pack(padx=2, pady=2, side="left")
polevar_btn = tk.Button(appbar, text="Polevar", bg="#444", fg="white", command=polevar)
polevar_btn.pack(padx=2, pady=2, side="left")
root.mainloop()
I am working on a project and I need to detect a change in the text box and change the text in another text box accordingly. Here is the function:
def work_change(event):
with open("uld.json", 'r', encoding="utf-8") as f:
data = json.load(f)
for i in range(len(data)):
if data[i]["code"] == int(e3.get("1.0", "end")) or data[i]["code1"] == int(e3.get("1.0", "end")):
description = data[i]["description"]
typeof = data[i]["type"]
print(description)
print(typeof)
e1.delete(1.0 ,"end")
e1.insert('end', description)
e2.delete(1.0 ,"end")
e2.insert('end', typeof)
break
I have tried everything and it just don't want to work. It detects the change but isn't changing the value in the text box. I don't know what to do and found no solution on web.
Here is my whole code:
import tkinter as tk
from tkinter import ttk, messagebox
import pandas as pd
import json
root = tk.Tk()
root.title("Polevar Generator")
root.geometry("800x500")
root.configure(background='#333')
labour_y = 50
labour_input = tk.Entry(root)
table_frame = None
canvas = None
container = None
# Function on data entry menu press
def data_entry():
global labour_input
global table_frame
global canvas
global container
if table_frame is not None:
table_frame.destroy()
if canvas is not None:
canvas.destroy()
if container is not None:
container.destroy()
labour_input.destroy()
labour_input = tk.Entry(root)
labour_input.place(x=30, y=20)
labour_input.delete(0, "end")
labour_input.insert(0, 'Enter Work Code')
labour_input.configure(state="disabled")
def labour_on_click(event):
labour_input.configure(state="normal")
labour_input.delete(0, "end")
global on_click_id
on_click_id = labour_input.bind('<Button-1>', labour_on_click)
def labour_submit(event):
global labour_code
labour_code = labour_input.get()
if labour_code != "Enter Work Code" and labour_code != "":
labour_input.delete(0, "end")
labour_input.insert(0, 'Enter Work Code')
labour_input.configure(state="disabled")
fetch_data(labour_code,0)
labour_input.bind('<Return>', labour_submit)
def fetch_data(code,factor):
description = ""
typeof = ""
with open("uld.json", 'r', encoding="utf-8") as f:
data = json.load(f)
for i in range(len(data)):
if data[i]["code"] == int(code) or data[i]["code1"] == int(code):
description = data[i]["description"]
typeof = data[i]["type"]
break
if description == "":
messagebox.showerror("Error", "Code not found.")
else: insert_labour(code,description,typeof)
def insert_labour(labour_code,description,typeof):
global labour_y
frame = tk.Frame(root)
frame.place(x=30, y=labour_y)
e1 = tk.Text(frame, width=20, height=4, fg="black", bg="#d1ffbd", font=('Arial', 10), wrap=tk.WORD)
e1.insert('end', description)
e1.configure(state="disabled")
e1.grid(row=0, column=1)
e2 = tk.Text(frame, width=5, height=4, fg="black", bg="#d1ffbd", font=('Arial', 10), wrap=tk.WORD)
e2.insert('end', typeof)
e2.configure(state="disabled")
e2.grid(row=0, column=2)
e3 = tk.Text(frame, width=5, height=4, fg="black", bg="#d1ffbd", font=('Arial', 10), wrap=tk.WORD)
e3.insert('end', labour_code)
e3.grid(row=0, column=3)
def work_change(event):
with open("uld.json", 'r', encoding="utf-8") as f:
data = json.load(f)
# Strip the newline character that Text widgets add automatically
code_input = e3.get("1.0", "end-1c").strip()
if not code_input: # Skip if empty
return
try:
code_input = int(code_input)
for i in range(len(data)):
if data[i]["code"] == code_input or data[i]["code1"] == code_input:
description = data[i]["description"]
typeof = data[i]["type"]
# Use string indices with quotes ("1.0" not 1.0)
e1.delete("1.0", "end")
e1.insert('end', description)
e2.delete("1.0", "end")
e2.insert('end', typeof)
break
except ValueError:
pass # Handle non-integer input
e3.bind("<KeyRelease>", work_change)
labour_y += 68
def display_csv_in_table():
global table_frame
global canvas
global container
if table_frame is not None:
table_frame.destroy()
if canvas is not None:
canvas.destroy()
if container is not None:
container.destroy()
df = pd.read_excel("uld.xlsx")
column_names = df.columns.tolist()
n_rows, n_cols = df.shape
container = tk.Frame(root, padx=20, pady=20)
container.pack(side="top", fill="both", expand=True)
canvas = tk.Canvas(container)
canvas.pack(side="left", fill="both", expand=True)
scroll_y = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scroll_y.pack(side="right", fill="y")
canvas.configure(yscrollcommand=scroll_y.set)
table_frame = tk.Frame(canvas)
canvas.create_window((0, 0), window=table_frame, anchor="nw")
col_widths = [5, 5, 50, 5 ,8, 15]
for j, col in enumerate(column_names):
if col =="nan":col=""
lbl = tk.Label(table_frame, text=col, width=col_widths[j % len(col_widths)], bg="lightgreen", relief="ridge", padx=5, wraplength=col_widths[j % len(col_widths)] * 10)
lbl.grid(row=0, column=j, sticky="nsew")
def load_rows():
for i in range(n_rows):
bg_color = "#f0f0f0" if i % 2 == 0 else "#ffffff"
for j in range(n_cols):
if str(df.iloc[i, j]) =="nan":df.iloc[i, j]=""
lbl = tk.Label(table_frame, text=str(df.iloc[i, j]), bg=bg_color, relief="ridge", padx=5, wraplength=col_widths[j % len(col_widths)] * 5, justify="left")
lbl.grid(row=i + 1, column=j, sticky="nsew", pady=2)
lbl.config(width=col_widths[j % len(col_widths)], justify="left")
table_frame.update_idletasks()
table_frame.grid_propagate(False)
canvas.config(scrollregion=canvas.bbox("all"))
print("Loaded")
def on_mousewheel(event):
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
canvas.bind_all("<MouseWheel>", on_mousewheel)
load_rows()
def uld():
display_csv_in_table()
def polevar():
global table_frame
global canvas
global labour_input
labour_input.destroy()
if table_frame is not None:
table_frame.destroy()
if canvas is not None:
canvas.destroy()
appbar = tk.Frame(root, bg="#444")
appbar.pack(fill='x', side="bottom")
uld_btn = tk.Button(appbar, text="ULD", bg="#444", fg="white", command=uld)
uld_btn.pack(padx=2, pady=2, side="left")
data_btn = tk.Button(appbar, text="Data Entry", bg="#444", fg="white", command=data_entry)
data_btn.pack(padx=2, pady=2, side="left")
polevar_btn = tk.Button(appbar, text="Polevar", bg="#444", fg="white", command=polevar)
polevar_btn.pack(padx=2, pady=2, side="left")
root.mainloop()
Thanks
Share Improve this question edited Mar 3 at 17:34 Karthik PK asked Mar 3 at 16:35 Karthik PKKarthik PK 92 bronze badges1 Answer
Reset to default 3There are a few issues in your code:
- Text widget indices need quotes - use
"1.0"
instead of1.0
- The
get("1.0", "end")
method includes a trailing newline character which causes the integer conversion to fail - use"end-1c"
to exclude it - You need to handle errors when converting to
int
Here's it working:
def work_change(event):
with open("uld.json", 'r', encoding="utf-8") as f:
data = json.load(f)
# Strip the newline character that Text widgets add automatically
code_input = e3.get("1.0", "end-1c").strip()
if not code_input: # Skip if empty
return
try:
code_input = int(code_input)
for i in range(len(data)):
if data[i]["code"] == code_input or data[i]["code1"] == code_input:
description = data[i]["description"]
typeof = data[i]["type"]
# Use string indices with quotes ("1.0" not 1.0)
e1.delete("1.0", "end")
e1.insert('end', description)
e2.delete("1.0", "end")
e2.insert('end', typeof)
break
except ValueError:
pass # Handle non-integer input