OpenPyXL and Tkinter | Cannot convert values to excel from a Entry Widget - python

I'm working on automating a Asset Collection excel sheet for my job and I am trying to write values to cells in a single row based of the answer of users in a Entry Widget in Tkinter. The function that I have that finds the next empty row works fine based off the print statement it writes matching the next empty excel row. The GUI appears fine and doesn't give me issues off the other scripts that its connected to. When I try to write values to the excel sheet via a button that runs function that both finds the next empty row and writes values to its appropriate line, it throws the error below at me.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "c:\Users\cknuth\OneDrive - Mohawk Honda\Python Project\Asset Collection Automation\NewAsset.py", line 31, in find_and_write_row
sheet.cell(row = next_empty_row, column=1).value = asset_number
File "C:\Users\cknuth\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\openpyxl\cell\cell.py", line 218, in value
self._bind_value(value)
File "C:\Users\cknuth\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\openpyxl\cell\cell.py", line 187, in _bind_value
raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert <tkinter.StringVar object at 0x000002AA4A99C130> to Excel
Here is my code:
import openpyxl
import os
from tkinter import *
import tkinter as tk
asset_number = StringVar()
serial_number = StringVar()
device_type = StringVar()
device_make = StringVar()
device_model = StringVar()
company = StringVar()
dollar_value = StringVar()
user = StringVar()
location = StringVar()
department = StringVar()
notes = StringVar()
def find_and_write_row():
os.getcwd()
wb = openpyxl.load_workbook('Mohawk Auto Group - Asset Colletion Automated.xlsx', data_only=False)
sheet=wb.get_sheet_by_name('Asset Collection Sheet')
last_row = sheet.max_row
for row in range(last_row + 1, sheet.max_row + 100):
if not sheet.cell(row=row, column=1).value:
next_empty_row = row
break
print(next_empty_row)
if next_empty_row:
sheet.cell(row = next_empty_row, column=1).value = asset_number
sheet.cell(row = next_empty_row, column=2).value = serial_number
sheet.cell(row = next_empty_row, column=3).value = device_type
sheet.cell(row = next_empty_row, column=4).value = device_make
sheet.cell(row = next_empty_row, column=5).value = device_model
sheet.cell(row = next_empty_row, column=6).value = company
sheet.cell(row = next_empty_row, column=7).value = dollar_value
sheet.cell(row = next_empty_row, column=8).value = user
sheet.cell(row = next_empty_row, column=9).value = location
sheet.cell(row = next_empty_row, column=10).value = department
sheet.cell(row = next_empty_row, column=11).value = notes
wb.save("Mohawk Auto Group - Asset Colletion Automated.xlsx")
def new_asset_gui(root):
root.configure(bg='black')
root.title("New Asset")
root.geometry("600x400")
label1 = Label(root, text="Asset Tag #", bg="black", foreground="white")
label1.grid(row=0, column=0, padx=10, pady=10)
entry1 = Entry(root , textvariable= asset_number.get())
entry1.grid(row=0, column=1, padx=10, pady=10)
label2 = Label(root, text="Serial Number", bg="black", foreground="white")
label2.grid(row=1, column=0, padx=10, pady=10)
entry2 = Entry(root , textvariable= serial_number.get())
entry2.grid(row=1, column=1, padx=10, pady=10)
label3 = Label(root, text="Device Type", bg="black", foreground="white")
label3.grid(row=2, column=0, padx=10, pady=10)
entry3 = Entry(root , textvariable= device_type.get())
entry3.grid(row=2, column=1, padx=10, pady=10)
label4 = Label(root, text="Device Make", bg="black", foreground="white")
label4.grid(row=3, column=0, padx=10, pady=10)
entry4 = Entry(root , textvariable= device_make.get())
entry4.grid(row=3, column=1, padx=10, pady=10)
label5 = Label(root, text="device_model", bg="black", foreground="white")
label5.grid(row=4, column=0, padx=10, pady=10)
entry5 = Entry(root , textvariable= device_model.get())
entry5.grid(row=4, column=1, padx=10, pady=10)
label6 = Label(root, text="company", bg="black", foreground="white")
label6.grid(row=5, column=0, padx=10, pady=10)
entry6 = Entry(root , textvariable= company.get())
entry6.grid(row=5, column=1, padx=10, pady=10)
label7 = Label(root, text="Dollar Value", bg="black", foreground="white")
label7.grid(row=6, column=0, padx=10, pady=10)
entry7 = Entry(root , textvariable= dollar_value.get())
entry7.grid(row=6, column=1, padx=10, pady=10)
label8 = Label(root, text="Assigned User", bg="black", foreground="white")
label8.grid(row=7, column=0, padx=10, pady=10)
entry8 = Entry(root , textvariable= user.get())
entry8.grid(row=7, column=1, padx=10, pady=10)
label9 = Label(root, text="location", bg="black", foreground="white")
label9.grid(row=8, column=0, padx=10, pady=10)
entry9 = Entry(root , textvariable= location.get())
entry9.grid(row=8, column=1, padx=10, pady=10)
label10 = Label(root, text="Department", bg="black", foreground="white")
label10.grid(row=9, column=0, padx=10, pady=10)
entry10 = Entry(root , textvariable= department.get())
entry10.grid(row=9, column=1, padx=10, pady=10)
label11 = Label(root, text="Notes", bg="black", foreground="white")
label11.grid(row=10, column=0, padx=10, pady=10)
entry11 = Entry(root , textvariable= notes.get())
entry11.grid(row=10, column=1, padx=10, pady=10)
button1 = Button(root, text="Add to Sheet", command=find_and_write_row)
button1.grid(row=11, column=0, padx=10, pady=10)
I have tried changing some of the number values to IntVars, making sure its the right excel sheet. I even gave my code to ChatGTP to see if its even knows, but the AI just loops me around some very basic troubleshooting.
I can also confirm I did this get the line below to work before when it was assigned to a variable that got its values from its input, so it stopped working after I converted the the script into a GUI.
sheet.cell(row = next_empty_row, column=1).value = asset_number

Related

How do I store user data from a Tkinter GUI form?

I tried adding a text file to store all the data by building a function that opens and writes data to the file, the code seems to run but no data is getting added to the text file.
Here is the tkinter code.
name = StringVar()
email = StringVar()
usn = StringVar()
namelabel = ttk.Label(frame_content, text='Name',font=('Poppins', 10))
namelabel.grid(row=0, column=0, sticky='sw', padx=(2,10))
entry_name = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=name)
entry_name.grid(row=1, column=0)
emaillabel = ttk.Label(frame_content, text='Email',font=('Poppins', 10))
emaillabel.grid(row=0, column=1, sticky='sw', padx=10)
entry_email = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=email)
entry_email.grid(row=1, column=1, padx=10)
usnlabel = ttk.Label(frame_content, text='USN',font=('Poppins', 10))
usnlabel.grid(row=0, column=2, sticky='sw')
entry_usn = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=usn)
entry_usn.grid(row=1, column=2)
feedbacklabel = ttk.Label(frame_content, text='Feedback', font=('Poppins', 10))
feedbacklabel.grid(row=2, column=0, sticky='sw', pady=5)
textfeedback = Text(frame_content, width=94, height=15, font=('Poppins', 10))
textfeedback.grid(row=3, column=0, columnspan=3)
def submit():
print('Name:{}'.format(name.get()))
print('USN:{}'.format(usn.get()))
print('Email:{}'.format(email.get()))
print('Feedback:{}'.format(textfeedback.get(1.0, END)))
messagebox.showinfo(title='Submit', message='Thank you for your Feedback')
entry_name.delete(0, END)
entry_email.delete(0, END)
entry_usn.delete(0, END)
textfeedback.delete(1.0, END)
def open_file():
name_info = name.get()
email_info = email.get()
usn_info = usn.get()
feed_info = textfeedback.get(1.0, END)
data_file = open("data.txt", 'w')
data_file.write(name_info)
data_file.write(email_info)
data_file.write(usn_info)
data_file.write(feed_info)
data_file.close()
submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [submit(), open_file()])
mainloop()
EDIT
Your mistake can be at
submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [submit(), open_file()])
Call open_file() function first, then call submit() function, like:
submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [open_file(), submit()])

tkinter clickable Label to open details of Label [duplicate]

This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
Closed 6 months ago.
I'm trying to program an interface with tkinter, that shows users of my application as a list of Labels. The list is created from a database (created with sqlite3).
By clicking on each Label the program should open another window, showing details of the clicked user.
maybe do I need to use classes? (because for now, my script is not OOP)
root = Tk()
root.title("Utenti")
root.iconbitmap("D:\Willow\WilloW SW Gestionale")
root.geometry("365x600")
def open_user(name = str):
user = Tk()
user.title("Utenti")
user.iconbitmap("D:\Willow\WilloW SW Gestionale")
user.geometry("500x400")
#create entry
f_name_entry = Entry(user, width=30, state="disabled")
f_name_entry.grid(row=0, column=1, padx=20, pady=(10, 0))
P_iva_entry = Entry(user, width=30, state="disabled")
P_iva_entry.grid(row=1, column=1)
cell_number_entry = Entry(user, width=30, state="disabled")
cell_number_entry.grid(row=2, column=1)
tax_entry = Entry(user, width=30, state="disabled")
tax_entry.grid(row=3, column=1)
inps_entry = Entry(user, width=30, state="disabled")
inps_entry.grid(row=4, column=1)
# create text boxes
f_name_label = Label(user, text=name)
f_name_label.grid(row=0, column=0, pady=(10, 0))
P_iva_label = Label(user, text="p iva")
P_iva_label.grid(row=1, column=0)
cell_number_label = Label(user, text="cell number")
cell_number_label.grid(row=2, column=0)
tax_label = Label(user, text="tax")
tax_label.grid(row=3, column=0)
inps_label = Label(user, text="inps")
inps_label.grid(row=4, column=0)
i = 4
conn = sqlite3.connect("usersEsteso.db")
c = conn.cursor()
c.execute("SELECT *, oid FROM usersEsteso")
records = c.fetchall()
for record in records:
print_records = record[0]
users_lable = Label(root, bg="#778899")
users_lable.grid(row=i + 7, column=0, sticky="w", padx=5, pady=5, columnspan=3)
user_text = Label(users_lable, text=print_records)
user_text.grid(row=0, column=0, pady=5, padx=5, sticky="w")
#user_text.bind("<Enter>", open_user("sam"))
openUser_lable_button = Button(users_lable, text="apri " + record[0], command=lambda: open_user(record[0])) #here i showld pass the identification of the parent the button
openUser_lable_button.grid(row=1, column=0, pady=5, padx=5, sticky="e")
i = i + 1
conn.commit()
conn.close()
here the previous code, without database and simplyfied:
from tkinter import *
root = Tk()
root.title("Users")
root.geometry("365x600")
#global variables
i = 1
def open_user():
user = Tk()
user.title("User")
user.geometry("500x400")
#create entry
f_name_entry = Entry(user, width=150, state="normal")
f_name_entry.grid(row=0, column=1, padx=20, pady=(10, 0))
P_iva_entry = Entry(user, width=150, state="disabled")
P_iva_entry.grid(row=1, column=1, columnspan=2)
cell_number_entry = Entry(user, width=150, state="disabled")
cell_number_entry.grid(row=2, column=1, columnspan=2)
tax_entry = Entry(user, width=150, state="disabled")
tax_entry.grid(row=3, column=1, columnspan=2)
inps_entry = Entry(user, width=150, state="disabled")
inps_entry.grid(row=4, column=1, columnspan=2)
# create text boxes
f_name_label = Label(user, text="name")
f_name_label.grid(row=0, column=0, pady=(10, 0))
P_iva_label = Label(user, text="p iva")
P_iva_label.grid(row=1, column=0)
cell_number_label = Label(user, text="cell number")
cell_number_label.grid(row=2, column=0)
tax_label = Label(user, text="tax")
tax_label.grid(row=3, column=0)
inps_label = Label(user, text="inps")
inps_label.grid(row=4, column=0)
f_name_entry.insert(0, "here should be the name of the clicked user")
my_list = ["andrew", "sam", "Zoe"]
title_label = Label(root, text="List of Users")
title_label.grid(row=0, column=0, pady=(10,40))
for item in my_list:
print(i)
my_frame = Frame(root, bg="#a6a6a6")
my_label = Label(my_frame, text=item)
my_button = Button(my_frame, text="inspect user", command=open_user)
my_frame.grid(row=i, column=0, padx=10, pady=10)
my_label.grid(row=0, column=0, padx=10, pady=10)
my_button.grid(row=1, column=0, padx=10, pady=10)
i = i+1
root.mainloop()

Getting multiple results with one button (python/ tkiner)

I'm a beginner, and I've gathered a number of reference sites to make code!
But if you click the button, you'll see the value only for the last item.
Do you happen to know how to get each result in every row! And now you have to enter all the items to get the value, but even if there is a blank, I hope the result will come out for all the input boxes.
I think the code is a little tangled, but it's hard to solve. I'm posting the code's full text.
from tkinter import *
from tkinter import ttk
import csv
class App(ttk.Frame):
num_rows = 2
entry_list = []
def __init__(self, master, *args, **kwargs):
ttk.Frame.__init__(self, master, *args, **kwargs)
self.master = master
self.label_frame = ttk.Frame(self.master)
self.label_frame.grid()
self.label_list = []
label1 = Label(root, width=5, text="No.")
label2 = Label(root, width=12, text="Chip")
label3 = Label(root, width=12, text="Length[mm] : ")
label4 = Label(root, width=12, text="Width[mm] : ")
label5 = Label(root, width=12, text="Height[mm] : ")
label6 = Label(root, width=12, text="Watt[W] : ")
label7 = Label(root, width=12, text="Rjc[C/W] : ")
label8 = Label(root, width=12, text="h[W/㎡K] : ")
label9 = Label(master, width=12, text="Temp[C] : ",fg='red')
#grid
label1.grid(row=0, column=0, padx=1, pady=10)
label2.grid(row=0, column=1, padx=2, pady=10)
label3.grid(row=0, column=2, padx=2, pady=10)
label4.grid(row=0, column=3, padx=2, pady=10)
label5.grid(row=0, column=4, padx=2, pady=10)
label6.grid(row=0, column=5, padx=2, pady=10)
label7.grid(row=0, column=6, padx=2, pady=10)
label8.grid(row=0, column=7, padx=2, pady=10)
label9.grid(row=0, column=8, padx=2, pady=10)
##유동
self.Number_field = Entry(root, width=5)
self.Length_field = Entry(root, width=9)
self.Width_field = Entry(root, width=9)
self.Height_field = Entry(root, width=9)
self.Watt_field = Entry(root, width=9)
self.Rjc_field = Entry(root, width=9)
self.Temperature_field = Entry(root, width=9)
self.Number_field.grid(row=1, column=0, padx=1, pady=1)
self.Length_field.grid(row=1, column=2, padx=1, pady=1)
self.Width_field.grid(row=1, column=3, padx=1, pady=1)
self.Height_field.grid(row=1, column=4, padx=1, pady=1)
self.Watt_field.grid(row=1, column=5, padx=1, pady=1)
self.Rjc_field.grid(row=1, column=6, padx=1, pady=1)
self.Temperature_field.grid(row=1, column=8, padx=1, pady=1)
strs = StringVar()
strs2 = StringVar()
combx1 = ttk.Combobox(root, width=9, textvariable=strs)
combx1['values'] = (' Natural', ' Forced(Fan)')
combx1.current()
combx1.grid(column=7, row=1)
combx2 = ttk.Combobox(root, width=9, textvariable=strs2)
combx2['values'] = ('CPU', 'eMMC', 'PMIC')
combx2.grid(column=1, row=1)
combx2.current()
# Create a Submit Button and attached
button1 = Button(root, text="Submit", bg="black", fg="white", command=self.cal_Temp)
button1.grid(row=100, column=0, pady=10)
button2 = Button(root, text="Clear", fg="blue", command=self.clear_all)
button2.grid(row=100, column=1, pady=10)
button3 = Button(root, text="Add Row (+)", command=self.add_new)
button3.grid(row=102, column=0, pady=10)
button4 = Button(root, text="Delete Row (-)", command=self.delete)
button4.grid(row=102, column=1, pady=10)
button5 = Button(root, text="Export", command=self.writeToFile)
button5.grid(row=103, column=1, pady=10)
def writeToFile(self):
with open('Temperature_MJH.csv', 'a') as f:
w=csv.writer(f, quoting=csv.QUOTE_ALL)
w.writerow([self.Length_field.get()])
w.writerow([self.Width_field.get()])
w.writerow([self.Height_field.get()])
w.writerow([self.Watt_field.get()])
w.writerow([self.Rjc_field.get()])
w.writerow([self.Temperature_field.get()])
def clear_all(self):
self.Number_field.delete(0,END)
self.Length_field.delete(0, END)
self.Width_field.delete(0, END)
self.Height_field.delete(0, END)
self.Watt_field.delete(0, END)
self.Rjc_field.delete(0, END)
self.Temperature_field.delete(0, END)
#이거 지워도 되는지
self.Length_field.focus_set()
def cal_Temp(self):
Length = float(self.Length_field.get())
Width = float(self.Width_field.get())
Height = float(self.Height_field.get())
Watt = float(self.Watt_field.get())
Rjc = float(self.Rjc_field.get())
h = 1
Temperature = float(((Watt * 0.5) / (((Length * Width * 2) + (Length * 2) + (
Height * Width * 5)) / 1000)) / h + Rjc )
self.Temperature_field.insert(10,Temperature)
print(Temperature)
def add_new(self):
self.num_rows += 1
self.Number_field = Entry(root, width=5)
self.Length_field = Entry(root, width=9)
self.Width_field = Entry(root, width=9)
self.Height_field = Entry(root, width=9)
self.Watt_field = Entry(root, width=9)
self.Rjc_field = Entry(root, width=9)
self.Temperature_field = Entry(root, width=9)
self.Number_field.grid(row=self.num_rows, column=0, padx=1, pady=1)
self.Length_field.grid(row=self.num_rows, column=2, padx=1, pady=1)
self.Width_field.grid(row=self.num_rows, column=3, padx=1, pady=1)
self.Height_field.grid(row=self.num_rows, column=4, padx=1, pady=1)
self.Watt_field.grid(row=self.num_rows, column=5, padx=1, pady=1)
self.Rjc_field.grid(row=self.num_rows, column=6, padx=1, pady=1)
self.Temperature_field.grid(row=self.num_rows, column=8, padx=1, pady=1)
strs = StringVar()
strs2 = StringVar()
self.combx1 = ttk.Combobox(root, width=9, textvariable=strs)
self.combx1['values'] = (' Natural', ' Forced(Fan)')
self.combx1.current()
self.combx1.grid(row=self.num_rows, column=7)
self.combx2 = ttk.Combobox(root, width=9, textvariable=strs2)
self.combx2['values'] = ('CPU', 'eMMC', 'PMIC')
self.combx2.grid(row=self.num_rows, column=1)
self.combx2.current()
self.ics=self.num_rows
self.Number_field.insert(10, self.ics-1)
def delete(self):
self.num_rows -= 1
self.Number_field.destroy()
self.Length_field.destroy()
self.Width_field.destroy()
self.Height_field.destroy()
self.Watt_field.destroy()
self.Rjc_field.destroy()
self.Temperature_field.destroy()
self.combx1.destroy()
self.combx2.destroy()
self.ics -= 1
if __name__ == "__main__":
root = Tk()
root.configure(background='snow')
root.geometry("1000x450")
root.title("Expectation of Temp Calculator")
my_app = App(root)
root.mainloop()

how to skip an error in this code?? (Tkinter and openpyxl involved)

thanks for helping!
I have a spreadsheet that records my income and expenses, with dates, description, debit and credit amount. I wanted to used openpyxl to automate the process of adding values that are in a particular category, the program kind of works now, but the problem is: when I am searching for a phrase that don't exist in the sheet, the program crash, it can not do the things it suppose to before and after the search phrase that dont exist.
for example,
when i wanted to calculate the subtotal of search phrase "wage" and the put the subtotal into a target cell, it works fine. the problem comes out when i ask the program to look for something that isnt there.
I ask the program to look for wage, and create a subtotal, works fine and suppose to store the value at a defined target, when i ask the program to look for tax (which dont exist) the program showed nothing, then i ask the program to get the subtotal of rent (which exists). The program cant make the changes.
i am relatively new to all this.... so thanks again for helping! :)
from tkinter import *
import openpyxl as xl
window = Tk()
window.title("Excel Automation") # rename the title
def define_subtotal():
file_name = str(file_name_input_field.get()) # Collects the text from the text entry box
sheet_name = str(sheet_name_label_name_input_field.get()) # Collects the text from the text entry box
global wb # declare Workbook as global variable
wb = xl.load_workbook(file_name) # define workbook
sheet = wb[sheet_name] # Define sheet name
col_num = int(search_column_input_field.get())
search_phrase = search_phrase_input_field.get()
offset_col = int(offset_col_input_field.get())
target_col_num = int(target_col_input_field.get())
target_row_num = int(target_row_input_field.get())
total = 0
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, col_num)
if cell.value is None:
continue
else:
if search_phrase.casefold() in str(cell.value).casefold():
total += cell.offset(column=offset_col).value
total_description = sheet.cell(target_row_num, target_col_num + 1)
total_description.value = "Subtotal of : " + search_phrase
total_cell = sheet.cell(target_row_num, target_col_num)
total_cell.value = total
output.delete(0.0, END)
output.insert(END, "Subtotal for " + search_phrase + " defined")
else:
continue
def execute():
output.delete(0.0, END) # clear the text box
new_file_name = new_file_input_field.get()
output.insert(END, "Calculations complete!")
wb.save(new_file_name + ".xlsx")
def import_excel_file():
output.delete(0.0, END) # clear the text box
output.insert(END, "File imported")
sheet_name_label_name_input_field.config (state='disabled')
import_button.config (state='disabled')
file_name_input_field.config (state='disabled')
def close_window(): # exit function
window.destroy()
exit()
### CONTENTS
file_name_label = Label(window, text="File Name:")
file_name_input_field = Entry(window, width=38, borderwidth=2)
sheet_name_label = Label(window, text="Sheet Name:")
sheet_name_label_name_input_field = Entry(window, width=38, borderwidth=2)
import_button = Button(window, text="Import", padx=35, pady=0, command=import_excel_file)
search_phrase_label = Label(window, text="Search Phrase:")
search_phrase_input_field = Entry(window, width=38, borderwidth=2)
search_column_label = Label(window, text="Search Column:")
search_column_input_field = Entry(window, width=38, borderwidth=2)
offset_col_label = Label(window, text="Offset Column:")
offset_col_input_field = Entry(window, width=38, borderwidth=2)
target_col_label = Label(window, text="Target Column:")
target_col_input_field = Entry(window, width=38, borderwidth=2)
target_row_label = Label(window, text="Target Row:")
target_row_input_field = Entry(window, width=38, borderwidth=2)
new_file_label = Label(window, text="Name of New file:")
new_file_input_field = Entry(window, width=38, borderwidth=2)
define_subtotal_button = Button(window, text="Define Subtotal", padx=5, pady=0, command=define_subtotal)
execute_button = Button(window, text="Execute", padx=5, pady=0, command=execute)
# contents Column 2
status_label = Label(window, text="Status:")
output = Text(window, width=50, height=25, wrap=WORD, bg="white") # wrap=WORD : wrap text when in overflow.
output.insert(END, "Drag and drop file into project file\n"
"Define File Name and Sheet Name\n"
"Example: filename.xlsx /.xlsm/ xltx/.xltm")
exit_button = Button(window, text="exit", width=14, command=close_window)
### THE GRID
file_name_label.grid(row=0, column=0, columnspan=2, padx=0, pady=0, sticky=W)
file_name_input_field.grid(row=1, column=0, columnspan=2, padx=5, pady=3, sticky=W)
sheet_name_label.grid(row=2, column=0, columnspan=2, padx=0, pady=0, sticky=W)
sheet_name_label_name_input_field.grid(row=3, column=0, columnspan=2, padx=5, pady=3, sticky=W)
import_button.grid(row=4, column=0, columnspan=2, sticky=W, padx=5)
search_phrase_label.grid(row=5, column=0, columnspan=2, padx=0, pady=0, sticky=W)
search_phrase_input_field.grid(row=6, column=0, columnspan=2, padx=5, pady=5, sticky=W)
search_column_label.grid(row=7, column=0, columnspan=2, padx=0, pady=0, sticky=W)
search_column_input_field.grid(row=8, column=0, columnspan=2, padx=5, pady=5, sticky=W)
offset_col_label.grid(row=9, column=0, columnspan=2, padx=0, pady=0, sticky=W)
offset_col_input_field.grid(row=10, column=0, columnspan=2, padx=5, pady=5, sticky=W)
target_col_label.grid(row=11, column=0, columnspan=2, padx=0, pady=0, sticky=W)
target_col_input_field.grid(row=12, column=0, columnspan=2, padx=5, pady=5, sticky=W)
target_row_label.grid(row=13, column=0, columnspan=2, padx=0, pady=0, sticky=W)
target_row_input_field.grid(row=14, column=0, columnspan=2, padx=5, pady=5, sticky=W)
new_file_label.grid(row=15, column=0, columnspan=2, padx=0, pady=0, sticky=W)
new_file_input_field.grid(row=16, column=0, columnspan=2, padx=5, pady=5, sticky=W)
define_subtotal_button.grid(row=17, column=0, sticky=W, padx=5)
# GRID column 1
execute_button.grid(row=17, column=1, sticky=W, padx=5)
# GRID Column 2
status_label.grid(row=0, column=2, padx=5, sticky=W)
output.grid(row=1, column=2, rowspan=25, padx=5, sticky=NE)
exit_button.grid(row=17, column=2, sticky=E)
window.mainloop()
[enter image description here][1]
may be it will be a good option to use
try:
your code
except:
pass
And run your code inside of this from which you want to skip the error with this try except. if any exception happened then it will ignore this and will be running.

Python search CSV file and return result in Tkinter

Question has been updated since I've received an answer.
The question that now raises is how to get the values from the csv file when I have two "Players" next to each other.
from Tkinter import *
import csv
master = Tk()
b1 = StringVar()
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
b2 = StringVar()
v4 = StringVar()
v5 = StringVar()
v6 = StringVar()
a = Label(master, text="Player 1", font="Verdana 10 bold").grid(row=8, column=1, columnspan=2, pady=15)
b = Label(master, text="Player Name").grid(row=9, column=1, sticky='w')
c = Label(master, text="1st Service Percentage:").grid(row=10, column=1, sticky='w')
cc = Label(master, text="value", textvariable=v1)
d = Label(master, text="Points Won on 1st Serve: ").grid(row=11, column=1, sticky='w')
dd = Label(master, text="value", textvariable=v2)
e = Label(master, text="Points Won on 2nd serve:").grid(row=12, column=1, sticky='w')
ee = Label(master, text="value", textvariable=v3)
a22 = Label(master, text="Player 2", font="Verdana 10 bold").grid(row=8, column=3, columnspan=2, pady=15)
b22 = Label(master, text="Player Name").grid(row=9, column=3, sticky='w')
c22 = Label(master, text="1st Service Percentage:").grid(row=10, column=3, sticky='w')
cc22 = Label(master, text="value", textvariable=v4)
d22 = Label(master, text="Points Won on 1st Serve: ").grid(row=11, column=3, sticky='w')
dd22 = Label(master, text="value", textvariable=v5)
e22 = Label(master, text="Points Won on 2nd serve:").grid(row=12, column=3, sticky='w')
ee22 = Label(master, text="value", textvariable=v6)
def name():
with open("Service.csv") as fh:
for row in fh:
if (b1.get()) in row:
player_name = row[0:row.find(',')]
row = row.replace(player_name+',', '')
firstService = row[0:row.find(",")]
row = row.replace(firstService+',', '')
points_firstserve = row[0:row.find(",")]
row = row.replace(points_firstserve+',', '')
points_secondserve = row[0:row.find(",")]
row = row.replace(points_secondserve+',', '')
v1.set(firstService)
cc.grid(row=10, column=2, sticky='w')
v2.set(points_firstserve)
dd.grid(row=11, column=2, sticky='w')
v3.set(points_secondserve)
ee.grid(row=12, column=2, sticky='w')
if (b2.get()) in row:
player_name = row[0:row.find(',')]
row = row.replace(player_name + ',', '')
firstService = row[0:row.find(",")]
row = row.replace(firstService + ',', '')
points_firstserve = row[0:row.find(",")]
row = row.replace(points_firstserve + ',', '')
points_secondserve = row[0:row.find(",")]
row = row.replace(points_secondserve + ',', '')
v1.set(firstService)
cc.grid(row=10, column=2, sticky='w')
v2.set(points_firstserve)
dd.grid(row=11, column=2, sticky='w')
v3.set(points_secondserve)
ee.grid(row=12, column=2, sticky='w')
myb1 = Entry(master, textvariable=b1)
myb1.insert(10, "Andy Murray")
myb1.grid(row=9, column=2)
myb22 = Entry(master, textvariable=b2)
myb22.insert(10, "Novak Djokovic")
myb22.grid(row=9, column=4)
button1 = Button(master, text='Run', command=name, bg="light green", font="Verdana 9 bold")
button2 = Button(master, text='Quit', command=quit, bg="red", font="Verdana 9 bold")
button1.grid(row=15, column=2, ipadx=50, pady=10)
button2.grid(row=15, column=3, ipadx=50, pady=10, padx=5)
master.geometry("850x500+300+100")
master.bind('<Return>', name)
master.bind('<Escape>', quit)
mainloop()
Here I am not using v1,v2 and v3 text variables. Appending second player values beside first player values.
Enter "Andy Murray" hit Run next Enter "Novak Djokovic"
hit run. you will see results of second player beside first player values.
from tkinter import *
import csv
master = Tk()
b1 = StringVar()
#v1 = StringVar()
#v2 = StringVar()
#v3 = StringVar()
a = Label(master, text="Player 1", font="Verdana 10 bold").grid(row=8, column=1, columnspan=2, pady=15)
b = Label(master, text="Player Name").grid(row=9, column=1, sticky='w')
c = Label(master, text="1st Service Percentage:").grid(row=10, column=1, sticky='w')
cc = Label(master, text="")
d = Label(master, text="Points Won on 1st Serve: ").grid(row=11, column=1, sticky='w')
dd = Label(master, text="")
e = Label(master, text="Points Won on 2nd serve:").grid(row=12, column=1, sticky='w')
ee = Label(master, text="")
def name():
with open("service.csv") as fh:
for row in fh:
if (b1.get()) in row:
player_name = row[0:row.find(',')]
row=row.replace(player_name+',','')
#print(row)
firstService=row[0:row.find(",")]
row=row.replace(firstService+',','')
points_firstserve=row[0:row.find(",")]
row=row.replace(points_firstserve+',','')
points_secondserve=row[0:row.find(",")]
row=row.replace(points_secondserve+',','')
cc['text'] += " "+firstService
#v1.set(firstService)
cc.grid(row=10, column=2, sticky='w')
#v2.set(points_firstserve)
dd['text'] += " "+points_firstserve
dd.grid(row=11, column=2, sticky='w')
#v3.set(points_secondserve)
ee['text'] += " "+points_secondserve
ee.grid(row=12, column=2, sticky='w')
myb1 = Entry(master, textvariable=b1)
myb1.insert(10, "Andy Murray")
myb1.grid(row=9, column=2)
button1 = Button(master, text='Run', command=name, bg="light green", font="Verdana 9 bold")
button2 = Button(master, text='Quit', command=quit, bg="red", font="Verdana 9 bold")
button1.grid(row=15, column=2, ipadx=50, pady=10)
button2.grid(row=15, column=3, ipadx=50, pady=10, padx=5)
master.geometry("850x500+300+100")
master.bind('<Return>', name)
master.bind('<Escape>', quit)
mainloop()
from tkinter import *
import csv
master = Tk()
b1 = StringVar()
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
a = Label(master, text="Player 1", font="Verdana 10 bold").grid(row=8, column=1, columnspan=2, pady=15)
b = Label(master, text="Player Name").grid(row=9, column=1, sticky='w')
c = Label(master, text="1st Service Percentage:").grid(row=10, column=1, sticky='w')
cc = Label(master, text="value", textvariable=v1)
d = Label(master, text="Points Won on 1st Serve: ").grid(row=11, column=1, sticky='w')
dd = Label(master, text="value", textvariable=v2)
e = Label(master, text="Points Won on 2nd serve:").grid(row=12, column=1, sticky='w')
ee = Label(master, text="value", textvariable=v3)
def name():
with open("Service.csv") as fh:
for row in fh:
if (b1.get()) in row:
player_name = row[0:row.find(',')]
row=row.replace(player_name+',','')
#print(row)
firstService=row[0:row.find(",")]
row=row.replace(firstService+',','')
points_firstserve=row[0:row.find(",")]
row=row.replace(points_firstserve+',','')
points_secondserve=row[0:row.find(",")]
row=row.replace(points_secondserve+',','')
#
v1.set(firstService)
cc.grid(row=10, column=2, sticky='w')
v2.set(points_firstserve)
dd.grid(row=11, column=2, sticky='w')
v3.set(points_secondserve)
ee.grid(row=12, column=2, sticky='w')
myb1 = Entry(master, textvariable=b1)
myb1.insert(10, "Andy Murray")
myb1.grid(row=9, column=2)
button1 = Button(master, text='Run', command=name, bg="light green", font="Verdana 9 bold")
button2 = Button(master, text='Quit', command=quit, bg="red", font="Verdana 9 bold")
button1.grid(row=15, column=2, ipadx=50, pady=10)
button2.grid(row=15, column=3, ipadx=50, pady=10, padx=5)
master.geometry("850x500+300+100")
master.bind('<Return>', name)
master.bind('<Escape>', quit)
mainloop()
This will fetch numbers from csv row for specific player. Am placing the value beside value names in the GUI.
Hope this helps.

Categories