Tkinter label overlap - python

for one of my first little projects I coded a fitnesscalculator last evening. Which has 3 functionalities at the start: Calculating the 1RM, BMI and FFMI. I'm running into the problem of overlapping labels when I first calculate the 1RM and then the FFMI. I have already googled and looked for similar threads but I couldn't find an answer to my solutions as my Gui is and its functionalities are based around a combobox. Please excuse the rather messy code, but I have already tried several methods to deal with this problem
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
root = Tk()
root.geometry("400x400")
root.title("Fitness Calculator")
#dropdown
Options = ["1RM Calculator", "BMI Calculator", "FFMI Calculator"]
#functions
def picker(input):
global calculate_button
global bf_box
global bf_label
global result_label
global result2_label
global result3_label
calculate_button.destroy()
result_label.pack_forget()
result2_label.destroy()
result3_label.destroy()
bf_label.destroy()
bf_box.destroy()
selected = drop.get() #holt sich wert vom dropdown
####################RM CALCULATOR####################
if selected == Options[0]:
#labels
weight_label = Label(root,text="Enter your training weight here: ", padx=10, pady=10)
weight_label.grid(row=2, column=0, sticky=W)
reps_label = Label(root,text="Enter your repetitions here: ", padx=10)
reps_label.grid(row=3, column=0, sticky=W)
def calculate():
weight = int(weight_box.get())
reps = int(reps_box.get())
one_rm = round(weight*(36/(37-reps)), 2)
#Result
result_label = Label(root, text="Your 1RM is: " + str(one_rm) + " kg")
result_label.grid(row=4)
weight_box.delete(0,END)
reps_box.delete(0,END)
#Entryfields
weight_box = Entry(root)
weight_box.grid(row=2, column=1)
reps_box = Entry(root)
reps_box.grid(row=3, column=1)
#Calculate button
calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
calculate_button.grid(row=4,column=1,pady=10)
####################BMI CALC####################
if selected == Options[1]:
#LABELS
weight_label = Label(root,text="Enter your weight in kg here: ", padx=10, pady=10)
weight_label.grid(row=2, column=0, sticky=W)
height_label = Label(root,text="Enter your height in cm here: ", padx=10)
height_label.grid(row=3, column=0, sticky=W)
#ENTRY BOXES
weight_box = Entry(root)
weight_box.grid(row=2, column=1)
height_box = Entry(root)
height_box.grid(row=3, column=1)
def calculate():
weight = float(weight_box.get())
height = float(height_box.get())/100
bmi = round(weight/(height**2),0)
#Result
result_label = Label(root, text="Your BMI is: " + str(bmi))
result_label.grid(row=4)
weight_box.delete(0,END)
height_box.delete(0,END)
#Calculate button
calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
calculate_button.grid(row=4,column=1,pady=10)
####################FFMI####################
if selected == Options[2]:
calculate_button.destroy()
#LABELS
weight_label = Label(root,text="Enter your weight in kg here: ", padx=10,pady=5)
weight_label.grid(row=2, column=0, sticky=W)
height_label = Label(root,text="Enter your height in cm here: ", padx=10,pady=5)
height_label.grid(row=3, column=0, sticky=W)
bf_label = Label(root,text="Enter your estimated bodyfat % here: ", padx=10,pady=5)
bf_label.grid(row=4, column=0, sticky=W)
#ENTRY BOXES
weight_box = Entry(root)
weight_box.grid(row=2, column=1)
height_box = Entry(root)
height_box.grid(row=3, column=1)
bf_box = Entry(root)
bf_box.grid(row=4, column=1)
def calculate():
weight = float(weight_box.get())
height = float(height_box.get())/100
bf = float(bf_box.get())
total_bf = weight*(bf)
lean_weight = weight*(1-(bf/100))
ffmi = round((lean_weight/height**2),2)
adjusted_ffmi = ffmi + 6.1 * (1.8 - height)
#Result
result_label = Label(root, text="Lean Mass: " + str(lean_weight) + " kg")
result_label.grid(row=6, sticky=W, padx=5)
result_label2 = Label(root, text="FFMI: " + str(ffmi))
result_label2.grid(row=7, sticky=W, padx=5)
result_label3 = Label(root, text="adjusted-FFMI: " + str(adjusted_ffmi))
result_label3.grid(row=8,sticky=W, padx=5)
weight_box.delete(0,END)
height_box.delete(0,END)
bf_box.delete(0,END)
#Calculate button
calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
calculate_button.grid(row=5,column=1,pady=10)
calculate_button = Button(root,text="Calculate", width=16 )
calculate_button.grid(row=4,column=1,pady=10)
calculate_button.destroy()
#Dropdownbox
drop = ttk.Combobox(root, value=Options, state="readonly")
drop.current(0)
drop.grid(row=0)
drop.bind("<<ComboboxSelected>>", picker)
result_label = Label(root,text="test")
result_label.grid(row=4)
result2_label = Label(root,text="")
result2_label.grid(row=4)
result3_label = Label(root,text="")
result3_label.grid(row=4)
bf_label = Label(root)
bf_box = Entry(root)
picker(drop.current(0))
root.mainloop()
Here a Screenshot of the problem I'm referencing to:

You keep creating a new Label with name result_label in your calculate methods.
This piles the labels on top of each other, since the result_label.destroy() does not remove them from the grid.
Instead of destroying them, keep just one instance (which you already defined global) and then configure them with the new text:
result_label.config(text="Your BMI is: " + str(bmi))

Related

Im trying to get calculate two tkinter entries with a button

I have tried StringVar, I've tried set().
Note: The program successfully calculates the value and returns the answer in a seperate pop-up, but I would like it to display the answer in the readonly "yards" entry field as well.
import tkinter as tk
import tkinter.ttk as ttk
#Formats all of the visible elements of the tkninter GUI.Connects the buttons to their functions.
class MetersToYardsApp:
def __init__(self, parent):
topLevel = ttk.Frame(parent, padding=10)
topLevel.grid(column=0, row=0)
headerLabel = ttk.Label(topLevel, text="Meters to Yards Calculator", font="{Arial} 16 {bold}")
headerLabel.grid(column=0, row=0, sticky="nsew")
inputFrame = ttk.Frame(topLevel, padding=10)
inputFrame.grid(column=0, row=1, sticky="nsew")
metersLabel = ttk.Label(inputFrame, text="Meters:")
yardsLabel = ttk.Label(inputFrame, text="Yards:")
metersEntry = ttk.Entry(inputFrame)
yardsEntry = ttk.Entry(inputFrame, state="readonly")
metersLabel.grid(column=0, row=0, sticky="e")
yardsLabel.grid(column=0, row=1, sticky="e")
metersEntry.grid(column=1, row=0, pady=3)
yardsEntry.grid(column=1, row=1, pady=3)
buttonFrame = ttk.Frame(topLevel)
buttonFrame.grid(column=0, row=2, sticky='nsew')
clearButton = ttk.Button(buttonFrame, text="Clear", command=self.clear)
okayButton = ttk.Button(buttonFrame, text="Calculate", command=self.calculate)
clearButton.grid(column=0, row=0, padx=3)
okayButton.grid(column=1, row=0)
self.mainWindow = topLevel
self.metersEntry = metersEntry
self.yardsEntry = yardsEntry
#Clear Button
def clear(self):
# print("Clear")
self.metersEntry.delete(0, tk.END)
#Formats the Pop-up that displays the answer
def showAnswer(self, parent, text):
rootFrame = ttk.Frame(parent, padding=10)
rootFrame.grid(column=0, row=0)
headerLabel = ttk.Label(rootFrame, text="The Answer", font="{Arial} 14 {bold}")
headerLabel.grid(column=0, row=0)
answerLabel = ttk.Label(rootFrame, text=text, justify=tk.CENTER)
answerLabel.grid(column=0, row=1)
#Performs Calculations if input is valid.
def calculate(self):
# print("Calculate Meters: ", self.metersEntry.get())
try:
meters = float(self.metersEntry.get())
yards = meters * 1.094
except:
top2 = tk.Toplevel(self.mainWindow)
self.showAnswer(top2, "There was an Error.\n" + "Please Enter a Valid Number for Meters")
# print("Please Enter a Valid Number for Meters.")
return
print(meters, "Meters is ", yards, "Yards. ")
top2 = tk.Toplevel(self.mainWindow)
self.showAnswer(top2, str(meters) + " Meters is equivalent to " + "{:.2f} Yards.".format(yards))
return float(yards)
You do have to use DoubleVar to update the Entry element:
yards_entry_var = tk.DoubleVar(inputFrame, 0)
Then you should place it inside the Entry element 'textvariable':
yardsEntry = ttk.Entry(inputFrame, textvariable=yards_entry_var, state="readonly")
to use it outside the init function:
self.yards_entry_var = yards_entry_var
in the calculate function, after calculating the yards:
self.yards_entry_var.set(yards)
And finally, when you want to clear the value in the clear function:
self.yards_entry_var.set(0)

Can i do a calculation in two text boxes and get the result in an other one

i am new to programming and i am programming my first project and i want to know can i do a calculation in two text boxes and get the result to another one
And thank you guys
Here is my code:
from Tkinter import *
import Tkinter as tk
def add(x, y):
return x+y
root = tk.Tk()
root.geometry('340x275+50+50')
root.title('Calculator')
root.resizable(True, True)
root.iconbitmap("C://123//
icon.ico")
num_1 = Label(root,
text="First number :")
num_1.grid(row=1, column=1)
num_2 = Label(root,
text="Second number :")
num_2.grid(row=1, column=3)
textBox1 = Text(root,
height=2, width=10)
textBox1.grid(row=1, column=2)
input1 = textBox1.get("1.0",
END)
textBox2 = Text(root,
height=2, width=10)
textBox2.grid(row=1, column=4)
input2 = textBox2.get("1.0",
END)
textBox_result = Text(root,
height=2, width=40)
textBox_result.grid(row=3,
column=2)
btn_add = Button(root,
text="+", command=add(input1,
input2))
btn_add.grid(row=2, column=1)
root.mainloop()
As newbie tutorial. Try this;
from tkinter import *
root = Tk()
root.title("Sum Two Numbers With GUI Using Python Source Code")
width = 400
height = 280
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
#==============================METHODS========================================
def calculate():
if not num1.get() and not num2.get():
print("Please enter a number")
else:
res=int(num1.get())+int(num2.get())
lbl_text.config(text = "The answer is %d" % (res))
num1.set=""
num2.set=""
#==============================FRAMES=========================================
Top = Frame(root, bd=2, relief=RIDGE)
Top.pack(side=TOP, fill=X)
Form = Frame(root, height=200)
Form.pack(side=TOP, pady=20)
#==============================LABELS=========================================
lbl_title = Label(Top, text = "Sum Two Numbers With GUI Using Python Source Code", font=('arial', 12))
lbl_title.pack(fill=X)
lbl_num1 = Label(Form, text = "Number 1:", font=('arial', 14), bd=15)
lbl_num1.grid(row=0, sticky="e")
lbl_num2 = Label(Form, text = "Number 2:", font=('arial', 14), bd=15)
lbl_num2.grid(row=1, sticky="e")
lbl_text = Label(Form)
lbl_text.grid(row=2, columnspan=2)
#==============================ENTRY WIDGETS==================================
num1 = Entry(Form, font=(14))
num1.grid(row=0, column=1)
num2 = Entry(Form, font=(14))
num2.grid(row=1, column=1)
#==============================BUTTON WIDGETS=================================
btn_calculate = Button(Form, text="Calculate", width=45, command=calculate)
btn_calculate.grid(pady=25, row=3, columnspan=2)
Another one easy for you.
import tkinter as tk
from functools import partial
def findsum(l3, num1, num2):
n1 = int(num1.get())
n2 = int(num2.get())
n3 = n1 + n2
l3.config(text="Result = %d" % n3)
return
root = tk.Tk()
root.title("Xiith.com")
root.geometry("700x500")
number1 = tk.StringVar()
number2 = tk.StringVar()
l1 = tk.Label(root, text="Enter 1st number").place(x=20, y=60)
l2 = tk.Label(root, text="Enter 2nd number").place(x=20, y=120)
t1 = tk.Entry(root, textvariable=number1).place(x=200, y=60)
t2 = tk.Entry(root, textvariable=number2).place(x=200, y=120)
labelResult = tk.Label(root)
labelResult.place(x=250, y=200)
findsum = partial(findsum, labelResult, number1, number2)
b1 = tk.Button(root, text="ADD", command=findsum).place(x=200, y=300)
b2 = tk.Button(root, text="Cancel", command=root.destroy).place(x=250, y=300)
root.mainloop()

How to shoving tkinter function result in a new window?

I am trying to make a staffing calculator using GUI tkinter in python I expect to get the function calculation results once I fill all entries and click on calculate button in a new window (master) based on the entry but unfortunately I got an empty label in the new window also I am not reeving any error to fix, would you please help me?, here is my code and screen shot:
from tkinter import *
root = Tk()
root.title("Workload Staffing Calculator")
#Header
headerlab = Label(root, text="Please fill the below form and click calculate to get the required staff.").grid(row=0,columnspan=2,pady=20,padx=20)
#Inputs names
vollabel = Label(root, text="Volumes").grid(padx=0,pady=10)
ahtlabel = Label(root, text="AHT (sec.)").grid(padx=0, pady=10)
Occlabel = Label(root, text="Occupancy (%)").grid(padx=0, pady=10)
Shrinklabel = Label(root, text="Shrinkage (%)").grid(padx=0, pady=10)
weekendlabel = Label(root, text="Days Off").grid(padx=0, pady=10)
Shiftlabel = Label(root, text="Shift Duration (h)").grid(padx=0, pady=10)
#Entry inptus
volentry = Entry(root, width=10, borderwidth=3)
ahtentry = Entry(root, width=10, borderwidth=3)
occentry = Entry(root, width=10, borderwidth=3)
shrinkentry = Entry(root, width=10, borderwidth=3)
weekendentry = Entry(root, width=10, borderwidth=3)
shiftentry = Entry(root, width=10, borderwidth=3)
#shoving inputs on screen
volentry.grid(row=1, column=1, padx=20)
ahtentry.grid(row=2, column=1, padx=20)
occentry.grid(row=3, column=1, padx=20)
shrinkentry.grid(row=4, column=1, padx=20)
weekendentry.grid(row=5, column=1, padx=20)
shiftentry.grid(row=6, column=1, padx=20)
#Calculate Fuction
def calstaff() :
v = volentry.get()
a = ahtentry.get()
o = occentry.get()
s = shrinkentry.get()
w = weekendentry.get()
sh = shiftentry.get()
required = (int(v) * int(a)) / (int(sh) * 3600)
total = required * (7 / (7 - int(w))) * (1 + float(s))
newwindow = Tk()
newwindow.title("The required is: ")
result = Label(newwindow, textvariable=total).pack()
return result
#calculate button
calculate = Button(root, text="Calculate", command=calstaff)
calculate.grid(padx=20,pady=10)
root.mainloop()
It is not recommended to use Tk() more than once as it can interrupt the flow of the main loop. To create another window you should try using Toplevel()
Secondly, Instead of textvariable use text
Refer to the code below:
.
..
def calstaff() :
v = volentry.get()
a = ahtentry.get()
o = occentry.get()
s = shrinkentry.get()
w = weekendentry.get()
sh = shiftentry.get()
required = (int(v) * int(a)) / (int(sh) * 3600)
total = required * (7 / (7 - int(w))) * (1 + float(s))
newwindow = Toplevel() #TOPLEVEL() USED
newwindow.title("The required is: ")
result = Label(newwindow, text=total) #text instead of textvariable
result.pack()
newwindow.mainloop() #mainloop for newwindow
..

Tkinter GUI window not recognised in other functions

I am making a simple program that saves someone's name and their email address in a file. I am coding in python idle. My code is:
import random
from tkinter import *
num = (random.randint(1,3))
NOSa = open("CN.txt", "r")
NOS = (NOSa.read())
NOSa.close()
NOSa = open("CN.txt", "w")
if num == ("1"):
NOS = NOS + "a"
elif num == ("2"):
NOS = NOS + "v"
else:
NOS = NOS + "x"
NOSa.write(NOS)
NOSa.close()
def efg():
window2.destroy()
window2.mainloop()
exit()
def abc():
name = entry.get()
email = entry2.get()
window.destroy()
window2 = Tk()
window2.title("OP")
OT = Text(window2, width=30, height=10, wrap=WORD, background="yellow")
OT.grid(row=0, column=0, sticky=W)
OT.delete(0.0, END)
MT = "We have logged your details " + name
MT2 = ". We have a file saved called " + NOS
MT3 = ". Go check it out!"
OT.insert(END, MT)
OT.insert(END, MT2)
OT.insert(END, MT3)
new_file = open(NOS, "a")
new_file.write("This is ")
new_file.write(name)
new_file.write(" email address.")
new_file.write(" ")
new_file.write(email)
button2 = Button(window2, text="OK", width=5, command=efg)
button2.grid(row=1, column=0, sticky=W)
window.mainloop()
window2.mainloop()
window = Tk()
window.title("EN")
label = Label(window, text="Enter your name: ")
label.grid(row=0, column=0, sticky=W)
entry = Entry(window, width=20, bg="light green")
entry.grid(row=1, column=0, sticky=W)
label2 = Label(window, text="Enter your email address: ")
label2.grid(row=2, column=0, sticky=W)
entry2 = Entry(window, width=25, bg="light green")
entry2.grid(row=3, column=0, sticky=W)
button = Button(window, text="SUBMIT", width=5, command=abc)
button.grid(row=4, column=0, sticky=W)
window.mainloop()
When I run the code my first 2 boxes appear and run their code perfectly. However, when I click the button 'OK' I get this error:
NameError: name 'window2' is not defined
I use python-idle.
You may make windows2 global
window2 = None
def efg():
global window2
and later
def abc():
global window2

Python: Search function in GUI with regex requires global variables, but UnboundLocal Error

This is my first project I am a complete beginner, so my apologies.
I am attempting to create a inventory system with a GUI.
Where I ran into issues was handling all the data, I thought before learning SQLite I should attempt my own crappy data organizing that way I have a deeper understanding of the necessity of that library. Currently I have been stuck on the search function for weeks. My data is "organized" in a text file, it is comprised of a class with 6 variables. The variables are stored to the text file as follows; x1, x2, x3, x4, x5, x6.
Currently I am attempting to create a search function using regex that can find the entire class (x1-x6) by searching either x1, x2, or x3.
The problem I am having is that my search values (x_search_nick(x1), x_search_name(x2), or x_search_part(x3)) are all defined by entries in a search window within the GUI. When I hit the search button I would like it to display in a separate window the entire classes attributes of that search value. In order for it to be a separate window it needs to be a separate function, but at that point the search variables need to be defined globally. When making all search variables global I get "UnboundLocalError: unbound local error python local variable referenced before assignment", I believe because if searching using x1, x2, or x3 two of the variables will be empty? Either way I've tried setting it up in many different ways and can't seem to find the right way.
I also am very bad at phrasing this entire question so I will just throw my code out there and hopefully with this info and the code the problem will be easier to see. Along with the code I have a text file Reagent_To_List.txt. Again this is my first project, organization and such are a wreck.
Thank you.
from tkinter import *
import tkinter.messagebox
import re
#Tkinter Basics______________________________________________
root = Tk()
#Files to open_______________________________________________
Reagent_To_List_file = open("Reagent_To_List.txt","w")
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
#Class_____________________________________
class Reagent:
def __init__(self, Nickname, Name, Part_Num, Lot_Num, Expiration,
Manufacteur, ):
self.Nickname = Nickname
self.Name = Name
self.Part_Num = Part_Num
self.Lot_Num = Lot_Num
self.Expiration = Expiration
self.Manufacteur = Manufacteur
#Functions_________________________________
class New_Reagent_Button_1:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.New_Reagent_button =Button(topFrame, text="New Reagent",fg="Black", width=75, height=3, relief=RAISED, bd=18,command = self.new_Reg)
self.New_Reagent_button.grid(row=0, column=0)
def new_Reg(self):
newwin = Toplevel(root)
newwin.geometry("450x500")
Enter_Nick = Label(newwin, text = "Enter Nickname: ", bd = 25)
Enter_Nick.grid(row=0, column=0)
x = Entry(newwin, bd = 5, width=30)
x.grid(row=0, column=1)
Enter_Chem_Name = Label(newwin, text="Chemical Name: ", bd = 25)
Enter_Chem_Name.grid(row=1, column=0)
x_1 = Entry(newwin, bd=5, width=30)
x_1.grid(row=1, column=1)
Enter_Part = Label(newwin, text="Part Number: ", bd=25)
Enter_Part.grid(row=2, column=0)
x_2 = Entry(newwin, bd=5, width=30)
x_2.grid(row=2, column=1)
Enter_Lot = Label(newwin, text = "Lot Number: ", bd= 25)
Enter_Lot.grid(row=3, column=0)
x_3 = Entry(newwin, bd=5, width=30)
x_3.grid(row=3, column=1)
Enter_Exp = Label(newwin, text = "Expiration Date: ", bd= 25)
Enter_Exp.grid(row=4, column=0)
x_4 = Entry(newwin, bd=5, width=30)
x_4.grid(row=4, column=1)
Enter_Manu = Label(newwin, text = "Manufacteur: ", bd= 25)
Enter_Manu.grid(row=5, column=0)
x_5 = Entry(newwin, bd=5, width=30)
x_5.grid(row=5, column=1)
def Done_Save(x):
input = x.get()
input_1 = x_1.get()
input_2 = x_2.get()
input_3 = x_3.get()
input_4 = x_4.get()
input_5 = x_5.get()
Reagent_To_List = (Reagent(x,x_1, x_2, x_3, x_4, x_5))
Reagent_To_List_file.write(str(input + ", "))
Reagent_To_List_file.write(str(input_1 + ", "))
Reagent_To_List_file.write(str(input_2 + ", "))
Reagent_To_List_file.write(str(input_3 + ", "))
Reagent_To_List_file.write(str(input_4 + ", "))
Reagent_To_List_file.write(str(input_5))
Reagent_To_List_file.write("\n")
Reagent_To_List_file.flush()
Save_New_Reg = Button(newwin, text="Done/Save", bd=5, height=2, width= 8, command= lambda: Done_Save(x))
Save_New_Reg.grid(row=6, column=0)
Done_New_Reg = Button(newwin, text ="Exit", bd = 5, height = 2, width = 8, command = newwin.destroy)
Done_New_Reg.grid(row = 6, column = 2)
newwin.mainloop()
class Search_Button:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.Search_button =Button(topFrame, text="Search For Reagent", fg="Black", width=75, height=3, relief=RAISED, bd=18, command = self.Search)
self.Search_button.grid(row=1, column=0)
def Search(self):
newwin = Toplevel(root)
newwin.geometry("610x400")
Enter_Search = Label(newwin, text="Enter\n Nickname: ", bd=25)
Enter_Search.grid(row=0, column=0)
global x_search_nick
x_search_nick = Entry(newwin, bd=5, width=50)
x_search_nick.grid(row=0, column=1)
Enter_Search = Label(newwin, text="Enter\n Chemical Name: ", bd=25)
Enter_Search.grid(row=3, column=0)
global x_search_name
x_search_name = Entry(newwin, bd=5, width=50)
x_search_name.grid(row=3, column=1)
Enter_Search = Label(newwin, text="Enter\n Part #: ", bd=25)
Enter_Search.grid(row=6, column=0)
global x_search_part
x_search_part = Entry(newwin, bd=5, width=50)
x_search_part.grid(row=6, column=1)
Done_New_Search = Button(newwin, text = "Exit", bd = 5, height = 2, width = 8, command = newwin.destroy)
Done_New_Search.grid(row = 9, column = 2)
B_Search = Button(newwin, text="Search", bd=5, height=2, width=8, command= self.Search_Function)
B_Search.grid(row=9, column=0)
def Search_Function(self):
newwin = Toplevel(root)
newwin.geometry("550x700")
Results_Header = Label(newwin, text="Search Results", font=("Times New Roman", 16), height=5, width=10)
Results_Header.grid(row=0, column=1)
Search_Results_List = Listbox(newwin, bd=3, height=20, width=50)
Search_Results_List.grid(row=10, column=4)
regex_nick = (x_search_nick.get()) + r"([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+)"
pattern_nick = re.compile(regex_nick)
with open("Reagent_To_List.txt", "r") as f:
contents = f.read()
matches_nick = pattern_nick.finditer(contents)
for match_nick in matches_nick:
print(match_nick)
return (match_nick)
if match_nick.group(1) == x_search_nick.get():
Search_Results_List.insert(1, x_search_nick.get() + ", " + match_nick.group(2) + ", " + match_nick.group(3) + ", " + match_nick.group(4) + ", " + match_nick.group(5) + ", " + match_nick.group(6))
regex_name = (r"([a-zA-z0-9\-\/]+),\s" + x_search_name.get() + ",\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+)")
pattern_name = re.compile(regex_name)
with open("Reagent_To_List.txt", "r") as f:
contents = f.read()
matches_name = pattern_name.finditer(contents)
for match_name in matches_name:
print(match_name)
return (match_name)
if match_name.group(2) == x_search_name:
Search_Results_List.insert(1, match_name.group(1) + ", " + x_search_name.get() + ", " + match_name.group(3) + ", " + match_name.group(4) + ", " + match_name.group(5) + ", " + match_name.group(6))
regex_part = (r"([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+),\s" + (x_search_part.get()) + ",\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+),\s([a-zA-z0-9\-\/]+)")
pattern_part = re.compile(regex_part)
with open("Reagent_To_List.txt", "r") as f:
contents = f.read()
matches_part = pattern_part.finditer(contents)
for match_part in matches_part:
print(match_part)
return (match_part)
if match_part.group(3) == x_search_part:
Search_Results_List.insert(1, match_part.group(1) + ", " + match_part.group(2) + ", " + x_search_part.get() + ", " + match_part.group(4) + ", " + match_part.group(5) + ", " + match_part.group(6))
scrollbar = Scrollbar(newwin, orient="vertical")
scrollbar.config(command=Search_Results_List.yview)
scrollbar.grid(row=10, column=5, sticky="ns")
#except:
# Error_Header = Label(newwin, text="Search Yielded No Results", width = 30, height = 20, font= ("Times New Roman",20) )
#Error_Header.grid(row=5, column=4)
#print(error)
#Buttons____________________________________
New_b = New_Reagent_Button_1(root)
Search_b = Search_Button(root)
button_Edit_Reagent = Button(topFrame, text="Edit Reagent", fg="Black", width = 75, height = 3, relief = RAISED,bd= 18)
button_Delete_Reagent = Button(topFrame, text="Delete Reagent", fg="Red", width = 75, height = 3, relief = RAISED,bd= 18)
button_See_Reagent_List = Button(topFrame, text="See Reagent List", fg="Black", width = 75, height = 3, relief = RAISED,bd= 18)
button_Check_Expired = Button(topFrame, text="Check Expired", fg="Red", width = 75, height = 3, relief = RAISED,bd= 18)
button_Done = Button(topFrame, text="Done", fg="Red", width = 75, height = 3, relief = RAISED,bd= 18,command = root.destroy)
button_Edit_Reagent.grid(row=6, column=0)
button_Delete_Reagent.grid(row=7, column=0)
button_See_Reagent_List.grid(row=9, column=0)
button_Check_Expired.grid(row=11, column=0)
button_Done.grid(row=12, column=0)
root.mainloop()
It seems to me the Reagent_To_List.txt file, which is created outside of the scope of the Search_Function, is causing your issue.
If you add a txt_file argument in the Search_Function(self, txt_file) and replace all the Reagent_To_List.txt, within the function, with txt_file, then call the function Search_Function(root, "Reagent_To_List.txt") it should work.

Categories