Как получить возвращенное значение функции и ввести этот вывод в соответствующее поле в пользовательском интерфейсе с помощью tkinter и python - PullRequest
0 голосов
/ 04 марта 2020

Я создал функцию, которая вычисляет классификацию фрахта и возвращает целочисленное значение.

def Calculate_Class(length, width, height, weight):

    cubic_inches = length*width*height #calculate cubic inches in^3
    cubic_feet = cubic_inches/1728 #convert cubic in^3 to cubic ft^3
    density = weight/cubic_feet #calculate density

    if (density > 50): #if density of cargo is over 50 pounds
        classification = 50
    elif (density > 30 and density < 50): #if density is greater than 30 and less than 35
        classification = 55
    elif (density > 30 and density < 35):
        classification = 60
    elif (density > 22.5 and density < 30):
        classification = 65
    elif (density > 15 and density < 22.5):
        classification = 70
    elif (density > 13.5 and density < 15):
        classification = 77.5
    elif (density > 12 and density < 13.5):
        classification = 85
    elif (density > 10.5 and density < 12):
        classification = 92.5
    elif (density > 9 and density < 10.5):
        classification = 100
    elif (density > 8 and density < 9):
        classification = 110
    elif (density > 7 and density < 8):
        classification = 125
    elif (density > 6 and density < 7):
        classification = 150
    elif (density > 5 and density < 6):
        classification = 175
    elif (density > 4 and density < 5):
        classification = 200
    elif (density > 3 and density < 4):
        classification = 250
    elif (density > 2 and density < 3):
        classification = 300
    elif (density > 1 and density < 2):
        classification = 400
    elif (density < 1):
        classification = 500

    return classification

Я пытаюсь выяснить, как ввести возвращаемое значение функции Calculate_Class и ввести возвращенное целое число в Поле «Класс» в пользовательском интерфейсе. Например, если классификация равна 50, целое число 50 будет вставлено в поле «Класс» после заполнения полей длины, ширины, высоты, веса и нажатия кнопки для запуска «Расчет класса». Кнопка ".

GUI

Вот дополнительный код, относящийся к функции, которая получает входные данные для длины, ширины, высоты и пользовательского интерфейса.

# this function gets the inputs from the user

def RunFunction():

    origin_zip = int(e1.get()) #gets entries stores data here
    destination_zip = int(e2.get())
    handling_unit = [e3.get()]
    pieces = [e4.get()]
    description = [e5.get()]
    length = [e6.get()]
    width = [e7.get()]
    height = [e8.get()]
    weight = [e9.get()]
    classification = []


# the follow methods generate the labels, entry fields, and format the positioning of the widgets

l6 = Label(master, text = " Length").grid(row = 5, column = 1, sticky = W, pady = 1)
l7 = Label(master, text = " Width").grid(row = 6, column = 1, sticky = W, pady = 1)
l8 = Label(master, text = " Height").grid(row = 7, column = 1, sticky = W, pady = 1)
l9 = Label(master, text = " Weight").grid(row = 8, column = 1, sticky = W, pady = 1)
l10 = Label(master, text = " Class").grid(row = 9, column = 1, sticky = W, pady = 1)

e6 = Entry(master, borderwidth=5, width=10) #length(s)
e7 = Entry(master, borderwidth=5, width=10) #width(s)
e8 = Entry(master, borderwidth=5, width=10) #height(s)
e9 = Entry(master, borderwidth=5, width=10) #weight(s)
e10 = Entry(master, borderwidth=5, width=10) #class(s)

#the 40, 42, 44, 200 values are placeholders to test the function
b1 = Button(master, text = "Caculate Class", bg="yellow", 
padx=10, pady=25,command=lambda:Calculate_Class(40, 42, 44, 200)) #Calculate Class Button

b1.grid(row = 12, column = 1, sticky = E) # Calculate Class Button Positioning




1 Ответ

1 голос
/ 04 марта 2020

Вам нужна промежуточная функция, разработанная специально для кнопки. Кнопка вызывает функцию, функция выбирает значения из формы, вызывает Calculate_Class, а затем добавляет возвращаемое значение к GUI.

Например:

def set_class():

    # get the inputs
    length = int(e6.get())
    width = int(e7.get())
    height = int(e8.get())
    weight = int(e9.get())

    # calculate the classification
    classification = Calculate_Class(length, width, height, weight)

    # insert the classification into the form
    e10.delete(0, "end")
    e10.insert("end", classification)
...
b1 = Button(..., command=set_class)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...