Why is there an error when finding median in tkinter?

Viewed 83

I am writing a program using tkinter, to find the mean or median (depending on which one the user picks). While finding the mean works, the median only works when I print the value (rather than config the text).

I evaluated (using eval()) the values to find the median, but it gives the error below:

TypeError: can only concatenate str (not int) to str.

Here is a small part of my code:

from tkinter import *
import statistics

root = Tk()

class stats:

    def __init__(self, constant):

        # Determines the type of stat used. e.g-> mean, median, mode, etc...
        self.types_list = ["mean", "median"]
        self.type = self.types_list[1]

        self.values = []

        self.answer_label = Label(constant, text = "", bg = "light green")
        self.answer_label.place(relx = .2, rely = .7, relwidth = .3, relheight = .2)

        self.type_label = Label(constant, text = "It is set to Median", bg = "light green")
        self.type_label.place(relx = .843, rely = 0, relwidth = .15, relheight = .1)

        self.input_data = Entry(constant)
        self.input_data.place(relx = .45, rely = .05, relwidth = .25, relheight = .05)

        self.check = Button(constant, text = "Check", bg = "red", command = self.get_values)
        self.check.place(relx = .65, rely = .05, relwidth = .1, relheight = .05)

        self.mean = Button(constant, text = "Mean", command = self.set_mean)
        self.mean.place(relx = .4, rely = .5, relwidth = .2, relheight = .2)

        self.median = Button(constant, text = "Median", command = self.set_median)
        self.median.place(relx = .2, rely = .5, relwidth = .2, relheight = .2)

    def set_mean(self):

        self.type = self.types_list[0]
        self.type_label.config(text = "It is set to Mean")

    def set_median(self):

        self.type = self.types_list[1]
        self.type_label.config(text = "It is set to Median")

    def get_values(self):

        # Iterates through each number in entry widget

        self.values = self.input_data.get()

        # If it's mean
        if self.type == self.types_list[0]:

            mean = statistics.mean(eval(self.values))
            self.answer_label.config(text = mean)

        # If it's median
        elif self.type == self.type_label[1]:

            median = statistics.median(eval(self.values))
            self.answer_label.config(text = median)

s = stats(root)

mainloop()

However, when I print(statistics.median(eval(self.values))), without setting type to median, it works.

If anybody is willing to help, I would be honored! Or if there are any improvements- better variable names, simplicity (which I will fix), or even if my question was too long- then comment or include inside the answer. Also comment if you need further clarifications on my question.

0 Answers
Related