Exception in Tkinter callback: TypeError: float() argument must be a string or a number, not 'Event'

495 Views Asked by At
import tkinter as tk
import tkinter.font as font
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

s_data = pd.read_csv("https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv")

def predicted_score(hour :float):
    X = s_data.iloc[:, :-1].values  
    y = s_data.iloc[:, 1].values 
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) 
    linear_regressor = LinearRegression()  
    linear_regressor.fit(X_train, y_train)   
    y_pred = linear_regressor.predict(X_test)
    marks = linear_regressor.predict(hour)
    return marks

window = tk.Tk()
window.geometry("600x300")
tk.Label(window, text="Marks Predictor", justify= tk.CENTER, font = font.Font(size = 40,weight='bold')).pack()
tk.Label(window, text="Predict Percentage", justify= tk.LEFT, font = font.Font(size = 20,weight='bold')).pack()
hour_input = tk.Entry(window)
hour_input.bind("<Return>",predicted_score)
result_predicted_score = tk.Label(window).pack()
hour_input.pack()

window.mainloop()

The above code predicts the marks of the student according to the number of hours they have studied. The prediction is done using simple linear regression. I have used Tkinter for GUI. I am having "TypeError: float() argument must be a string or a number, not 'Event'" error while running this program.

1

There are 1 best solutions below

0
On

When you bind a function to an event, the function will always be called with an object representing the event. Your function, however, requires that the first paraemter is a float.

You need to either modify predicted_score to accept the event object, or bind to another function which accepts the event object and then calls predicted_score.

In your case, since the hour is coming from an entry I recommend you use a dedicated function. I'm assuming you want to display the score in result_predicted_score, so the callback function can do that, too:

def compute_score(event):
    hour = float(hour_input.get())
    score = predicted_score(hour)
    result_predicted_score.configure(text=str(score))
...
hour_input.bind("<Return>", compute_score)

However, for that to work result_predicted_score must be properly initialized. You are setting it to None. It needs to be defined like this:

result_predicted_score = tk.Label(windonw)
result_predicted_score.pack()