0
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()

上面的代码根据学生的学习小时数来预测学生的分数。预测是使用简单的线性回归完成的。我已经将 Tkinter 用于 GUI。运行此程序时出现“TypeError:float() 参数必须是字符串或数字,而不是“事件””错误。

4

1 回答 1

1

当您将函数绑定到事件时,将始终使用表示该事件的对象调用该函数。但是,您的函数要求第一个参数是浮点数。

您需要修改predicted_score以接受事件对象,或者绑定到另一个接受事件对象的函数,然后调用predicted_score.

在您的情况下,由于小时来自条目,我建议您使用专用功能。我假设你想在 中显示分数result_predicted_score,所以回调函数也可以做到这一点:

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)

但是,要使其正常工作,result_predicted_score必须正确初始化。您将其设置为None. 它需要像这样定义:

result_predicted_score = tk.Label(windonw)
result_predicted_score.pack()
于 2020-10-15T16:05:35.287 回答