I would like to know if anyone could help me with this problem. Im a beginner at Python, and im trying to create a program. The problem is that i want to search for a person in a stats database, and then get the result of the 5 most similar players based on stats. Now i only get one name, and cannot figure out what I am doing wrong.
This is the code that i have used, but it only displays 1 player, instead of the 5 players that are most similar.
import tkinter as tk
import pandas as pd
import os
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
def compare_players(player_name, data):
player = data[data['Player'] == player_name]
player_stats = player.select_dtypes(include=['float64'])
player_stats = (player_stats - player_stats.mean()) / player_stats.std()
data_stats = data.select_dtypes(include=['float64'])
data_stats = (data_stats - data_stats.mean()) / data_stats.std()
similarity = data_stats.dot(player_stats.T)
top_5 = data.iloc[similarity.iloc[0,:].sort_values(ascending=False).index[:5]]
return top_5
def run_search(folder_path, player_name, data):
result = compare_players(player_name, data)
for i, row in result[['Player', 'Team', 'Age']].iterrows():
tree.insert("", "end", values=(row['Player'], row['Team'], row['Age']))
def on_search():
player_name = entry.get()
run_search(folder_path, player_name, data)
def load_data():
global data
data = pd.DataFrame()
for file in os.listdir(folder_path):
if file.endswith(".xlsx"):
file_path = os.path.join(folder_path, file)
temp_data = pd.read_excel(file_path)
data = pd.concat([data, temp_data], axis=0)
root = tk.Tk()
root.withdraw()
folder_path = filedialog.askdirectory(initialdir = *Here i put the folder which contains many excel files*,
title = "Select folder")
load_data()
root = tk.Tk()
root.title("Player Comparison")
root.geometry("600x400")
label = tk.Label(root, text="Enter player name:")
entry = tk.Entry(root)
search_button = tk.Button(root, text="Search", command=on_search)
label.pack()
entry.pack()
search_button.pack()
tree = ttk.Treeview(root, columns=("Player", "Team", "Age"), show="headings")
tree.heading("Player", text="Player Name")
tree.heading("Team", text="Team")
tree.heading("Age", text="Age")
tree.pack(side="left", fill="y")
root.mainloop()
The code is most likely all over the place, but i try :D
Thanks for all answers in advance.
Related
Good day folks,
I created a simple GUI that let's the user browse through their files with tkinter's filedialog.
After picking one, python reads the data from the (excel) file, and with that creates a new .txt file.
Now after doing that, I would like python to make that .txt file pop up, so that the user gets to see the result.
How do I do this?
Edit for the bot-moderator- he wanted code examples:
File1.py
from contextlib import nullcontext
import File2 as tp
import tkinter as tk
from tkinter import StringVar, messagebox
from tkinter import filedialog
filename = None
def pickFile():
global filename
filename = filedialog.askopenfilename()
#Creating main window
master = tk.Tk()
masterWidth = 350
masterHeight = 250
master.iconbitmap('C:\...')#directory
master.title('Title')
# get the screen dimension
screen_width = master.winfo_screenwidth()
screen_height = master.winfo_screenheight()
# find the center point
center_x = int(screen_width/2 - masterWidth / 2)
center_y = int(screen_height/2 - masterHeight / 2)-100
# set the position of the window to the center of the screen
master.geometry(f'{masterWidth}x{masterHeight}+{center_x}+{center_y}')
#Creating startbutton
startButton = tk.Button (master, text="Start", height=1, width=3, command=lambda: tp.readFile(filename))
#Creating bladerknop
browseButton = tk.Button (master, text='browse...', command=pickFile)
browseLabel = tk.Label(master, text='Choose a file')
startButton.place(x=175,y=200)
browseButton.place(x=210,y=50)
browseLabel.place (x=110,y=52)
master.mainloop()
File2.py
import pandas as pd
import tkinter as tk
from tkinter import messagebox
#declaring variables for later use
data = None
def missingValues(path):
if path is not None:
data = pd.read_excel(path, header=None)
return data
else:
messagebox.showinfo('No file chosen', 'Choose a file first.')
def readFile(path):
data = missingValues(path)
with open("C:\...\newFile.txt", 'w') as newTxt:
count = 0
for index, row in data.iterrows():
code = data.loc[count,0]
price = toEightBits(data.loc[count,1])
newTxt.write(str(code))
newTxt.write(str(price))
newTxt.write("\n")
count += 1
newTxt.close()
My goal is to make a program that lets you edit audio metadata using tkinter, but I've gotten stuck. No matter what I try, the program will not edit the metadata. I am using a browse button so that you can choose any file. Here's my code:
import tkinter
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
import eyed3
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=400, height=300)
audio_file = None
def browse_files():
global audio_file
audio_file_path = askopenfilename(filetypes=(("Audio Files", "*.mp3"),))
audio_file = eyed3.load(audio_file_path)
file_chosen_label = tkinter.Label(root, text=audio_file_path)
file_chosen_label.pack()
return audio_file
def change_artist():
audio_file.tag.album_artist = artist_name.get()
audio_file.tag.save()
return
file_choose_label = tkinter.Label(root, text="Song file")
file_choose = tkinter.Button(root, text="Browse...", command=browse_files)
artist_label = tkinter.Label(root, text="Artist")
artist_name = tkinter.StringVar()
artist_entry = tkinter.Entry(root, textvariable=artist_name)
apply_button = tkinter.Button(root, command=change_artist, text="Apply")
file_choose_label.pack()
file_choose.pack()
artist_label.pack()
artist_entry.pack()
apply_button.pack()
canvas.pack()
root.mainloop()
What am I missing? No errors or anything.
OK, a couple of things:
Change:
def change_artist():
audio_file.tag.genre = artist_name
audio_file.tag.save()
return
To
def change_artist():
audio_file.tag.album_artist = artist_name.get()
audio_file.tag.save()
return
Then, change:
artist_entry = tkinter.Entry(root, textvariable="artist_name")
To:
artist_entry = tkinter.Entry(root, textvariable=artist_name)
Let me know how it goes.
EDIT, I would like to try something. Please change your change_artist function to:
def change_artist():
try:
audio_file.tag.album_artist = artist_name.get()
audio_file.tag.save()
except AttributeError as error:
print(type(audio_file), audio_file)
print(type(audio_file.tag))
raise error
Let me know what get's printed.
EDIT, One more time, try this:
def change_artist():
audio_file.initTag().album_artist = artist_name.get()
audio_file.tag.save()
I'm struggling again to figure out a way to update my tkinter listbox from a combobox selection.
What I want to happen is the user imports an excel file, the file is then read and all the sheets available on that workbook is displayed for the user to select (this part works - Combobox), once its selected it suppose to display all the headers in that excel sheet in a listbox so the user can select multiple headers. The headers changes depending on the sheet selected, so the listbox would have to update and display the new headers.
I figured out how to display it as a ComboBox and it'll update as different sheets are selected, but I need the ability to select multiple headers - hence why I'm trying to use a listbox.
I've pasted what I've got right now.
import pandas as pd
import os
import xlrd
from tkinter import *
from tkinter.filedialog import askopenfilename, asksaveasfilename
from tkinter.ttk import Combobox
import tkinter as tk
import re
import numpy as np
class myApp:
importedSheets = []
headers = []
reports = ['A','B','C','D']
# rb_select = IntVar()
def UploadAction(self):
self.filename = askopenfilename()
def SaveAction(self):
self.savelocation = asksaveasfilename()
def sheetnames(self):
self.xlssheets = xlrd.open_workbook(self.filename,on_demand=True)
importedSheets = self.xlssheets.sheet_names()
self.cbox_sheets.config(value=importedSheets) #updating the value of the combobox
return importedSheets
def headernames(self):
if self.reporttype.get(self.reporttype.curselection()) == self.reports[0]:
self.df = pd.read_excel(self.filename,sheet_name = self.cbox_sheets.get(),header = 1, index_col=0)
headers = list(self.df.columns)
self.headerselectors.config(values=headers)
def __init__(self,master):
self.filename = None
self.master = master
#---------------------------------------------------------------------#
# Creating Basic Frame Structure
#---------------------------------------------------------------------#
self.frame1 = Frame(master=master,relief=RAISED,borderwidth=1)
self.frame1.pack(padx=10,pady=10)
self.frame2 = Frame(master=master,relief=RAISED,borderwidth=1)
self.frame2.pack(padx=10,pady=10)
self.frame3 = Frame(master=master,relief=RAISED,borderwidth=1)
self.frame3.pack(padx=10,pady=10)
#---------------------------------------------------------------------#
# Frame 2 - Selecting Sheet and Header To Work with
#---------------------------------------------------------------------#
self.frame2a = Frame(master = self.frame2)
self.frame2b = Frame(master = self.frame2)
self.frame2r = Frame(master = self.frame2)
self.frame2a.pack(side=TOP)
self.frame2b.pack(side=LEFT)
self.frame2r.pack(side=RIGHT)
self.uploadLabel = Label(master = self.frame2a,text = '1) Select the file you want to import',font=(None,12,)).pack()
self.uploadButton = Button(master = self.frame2a,text = 'Import', command =lambda:self.UploadAction()).pack(padx=5,pady=5)
self.reporttype = Listbox(master=self.frame2a,height=4,selectmode=SINGLE,exportselection = False)
for x,reports in enumerate(self.reports):
self.reporttype.insert(x,reports)
self.reporttype.pack(padx=5,pady=5)
#---------------------------------------------------------------------#
# Selecting Sheets to work with:
#---------------------------------------------------------------------#
self.sheetLabel = Label(master = self.frame2b,text = '2) Select the sheet to extract',font=(None,12)).pack(padx=15)
self.cbox_sheets = Combobox(master = self.frame2b,values = self.importedSheets,postcommand = self.sheetnames)
self.cbox_sheets.pack(padx=5,pady=5)
#---------------------------------------------------------------------#
# Selecting Headers to Work with:
#---------------------------------------------------------------------#
self.headerLabel = Label(master = self.frame2r,text = '3) Select the header with data',font=(None,12)).pack(padx=15)
self.headerselectors = Combobox(master = self.frame2r,values = self.headers,postcommand = self.headernames)
self.headerselectors.pack(padx=5,pady=5)
if __name__ == '__main__':
root = Tk()
my_gui = myApp(root)
root.mainloop()
EDIT: The section that needs to be worked on is in: Selecting Headers to Work with (I don't know how to highlight on stackoverflow)
To create a dynamic listbox I had to bind it to a button:
self.headerLabel = Label(master = self.frame2r,
text = '3) Select the header with data',
font=(None,12)).pack(padx=15)
self.headers_button = Button(master = self.frame2r, text = 'Show Headers',command = self.headernames).pack()
self.headers_select = Listbox (master = self.frame2r,exportselection = False,selectmode=MULTIPLE)
self.headers_select.pack()
Once I created the basic listbox and button I added to my function def headernames(self):
def headernames(self):
if self.reporttype.get(self.reporttype.curselection()) == self.reports[0]:
self.df = pd.read_excel(self.filename,sheet_name = self.cbox_sheets.get(),header = 1, index_col=0)
headers = list(self.df.columns)
self.headers_select.delete(0,'end')
for x,header in enumerate(headers):
self.headers_select.insert(x,header)
Now everytime I click on the button "Show Headers" it'll clear the list and then add the new headers for the selected sheet.
I would like to create a table similar to Excel's style. It should be depending on the size of the array to show.
For this reason the table columns and rows are inside loop cycles.
In the first line I would have a combobox to select the value to filter.
Also the combobox is inside a loop cycle for the different columns number.
When the table is created I am not able to recognize which combobox is chosen.
How can I do?
Example:
import tkinter
from tkinter import ttk #per button, label etc
from tkinter.ttk import *
import numpy as np #for the matrix tools
def newselection(event, output):
print("Value selected:", event, output)
def ShowTableGui(MatrixToShowIn):
MatrixToShow=np.array(MatrixToShowIn)
RowNumber = MatrixToShow.shape[0]
ArrayCombo=[]
windowx=tkinter.Tk()
windowx.title("Table viewer")
buttonExit = ttk.Button(windowx, text="Close table", command=windowx.destroy)
# buttonExit = ttk.Button(windowx, text="Run Filter", command= lambda: Run_filter(MatrixToShow.shape[1]))
buttonExit.grid(column=0, row=0)
for Col in range (int(MatrixToShow.shape[1])):
ValuesInsert=MatrixToShow[:,Col] # values in column
ValuesInsert=[row[Col]for row in MatrixToShowIn]
ValuesInsert=list(set(ValuesInsert)) # values listed only once
ValuesInsert.sort()
ValuesInsert.insert(0,"*") # add * to filter all
comboExample0 = ttk.Combobox(windowx, state='readonly', values=ValuesInsert)
comboExample0.grid(column=Col+2, row=0)
comboExample0.bind("<<ComboboxSelected>>", lambda event:newselection(comboExample0.get(), "output"))
# comboExample0.bind("<<ComboboxSelected>>", lambda event:newselection(event, "output"))
ArrayCombo.append(comboExample0)
Select=comboExample0.get()
print(Select)
for Row in range (RowNumber):
b = Entry(windowx, text="")
b.grid(row=Row+1, column=Col+2)
b.insert(0,str(MatrixToShow[Row][Col]))
windowx.mainloop()
return()
MatrixToShowIn=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
ShowTableGui(MatrixToShowIn)
Finally I have the time to post the solution found thanks to your help:
from tkinter import *
from functools import partial
from tkinter.ttk import *
class ComboTest:
def __init__(self, MatrixToShow):
self.top = Tk()
self.top.title('Combos Test')
self.top_frame = Frame(self.top, width =400, height=400)
self.button_dic = {}
self.combos_dic = {}
self.var = StringVar()
self.top_frame.grid(row=0, column=1)
Button(self.top_frame, text='Exit',
command=self.top.destroy).grid(row=0,column=0, columnspan=5)
self.combos(MatrixToShow)
self.top.mainloop()
##-------------------------------------------------------------------
def combos(self,MatrixToShow):
b_row=1
Columns=[]
for com_num in range(len(MatrixToShow[0])):
Column=["*"]
for Row in range(len(MatrixToShow)):
Column.append(MatrixToShow[Row][com_num])
Columns.append(Column)
## note that the correct "com_num" is stored
# self.combos_dic[com_num] = "self.cb_combo_%d()" % (com_num)
e = Entry(self.top_frame)
e.insert(0, com_num)
e.insert(0, "Column")
e.grid(row=b_row, column=com_num)
b = Combobox(self.top_frame, state='readonly', values=Column)
b.bind("<<ComboboxSelected>>", partial(self.cb_handler, com_num))
b.current(0)
b.grid(row=b_row+1, column=com_num)
##----------------------------------------------------------------
def cb_handler( self, cb_number, event ):
print ("ComboNumber", cb_number, "SelectedValue", event.widget.get())
##=================================================================
MatrixToShowIn=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
CT=ComboTest(MatrixToShowIn)
Enjoy Roberto
Goal:
I am trying to have the script look through a directory named 'data' that is in the working directory of the script for excel workbooks. The script will then have a options menu of the different workbooks to choose from which will then give a selection of column names to choose from in a combo box above.
Results:
I was able to get it to read the default excel workbook upon start up but when I choose a different workbook the combo box does not update the column names.
I've tried to incorporate some sort of update function but I keep having trouble even running it because one or more things don't really line up. I am still new to python and tkinter so I would like some advice and suggestions to solve this problem.
import tkinter
from tkinter import ttk
from tkinter import *
import pandas as pd
def _quit():
root.quit()
root.destroy()
root = Tk()
root.title('BLURG')
root.geometry("1280x720")
path = os.chdir('Data')
filenames = os.listdir(path)
data_as_list = []
for filename in filenames:
if filename.endswith('.xlsx') or filename.endswith('.xls'):
data_as_list.append(filename)
clicked = StringVar()
options = data_as_list
clicked.set(options[0])
drop = OptionMenu(root, clicked, *options)
drop.pack(side="right")
data = pd.read_excel(clicked.get())
df = pd.DataFrame(data)
col_name = list(df.columns)
labelx = tkinter.Label(root, text="x-axis: ")
combox = ttk.Combobox(root, values=col_name)
labelx.pack(side="top")
combox.pack(side="top")
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
root.mainloop()
Using an update function with a postcommand fixed the problem.
...
def update_list():
data = pd.read_excel(clicked.get())
df = pd.DataFrame(data)
col_name = list(df.columns)
combox['values'] = col_name
labelx = tkinter.Label(root, text="x-axis: ")
combox = ttk.Combobox(root, postcommand=update_list)
...