Python: отображение возвращенного текста из функции с помощью кнопок и меток - PullRequest
0 голосов
/ 07 ноября 2019

Я создаю программу для создания различных упражнений, которые помогут с потерей веса. Функция генерирует упражнение, и количество этого упражнения вы должны сделать. Я отображаю их, используя метки в окне tkinter.

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

Isможно ли это сделать?

from tkinter import *
import random as r

exercises = ["star jumps", "press ups", "sit ups", "burpees", "bicycle crunches"] #array of exercises
eChoice = "" #declare variable for exercise choice
amount = "" #declare variable for amount of exercises
def exercise():
    x = r.randint(1, 4)
    if x == 1:
        #exercise
        eChoice = r.choice(exercises)
        amount = r.randint(10, 30)
    elif x == 2:
        #walk
        eChoice = "walk"
        amount = r.randint(1,3) #miles
    elif x == 3:
        #cycle
        eChoice = "cycle"
        amount = r.randint(1,3) #miles
    else:
        #swim
        eChoice = "swim"
        amount = r.randint(5,10) #lengths of a pool
    return eChoice, amount


myGUI = Tk() #create window

myGUI.title("Weight Loss Program") #title of the window
myGUI.configure(bg="deepskyblue") #background colour
exerciseButton = Button(myGUI, text="Generate Exercise", fg="mediumpurple", command=exercise) #create button that calls exercise function
exerciseButton.pack()
name = "Name: ", eChoice
exerciseLabel = Label(myGUI, text=name, fg="mediumpurple") #create label for exercise name
exerciseLabel.pack()
description = "Amount: ", amount
exerciseDescription = Label(myGUI, text=description, fg="mediumpurple") #create label for exercise name
exerciseDescription.pack()

myGUI.mainloop()```

1 Ответ

1 голос
/ 07 ноября 2019

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

Решение:

from tkinter import *
import random as r

exercises = ["star jumps", "press ups", "sit ups", "burpees", "bicycle crunches"] #array of exercises
eChoice = "" #declare variable for exercise choice
amount = "" #declare variable for amount of exercises
def exercise():
    global exerciseLabel
    global exerciseDescription
    global eChoice

    x = r.randint(1, 4)
    if x == 1:
        #exercise
        eChoice = r.choice(exercises)
        amount = r.randint(10, 30)
    elif x == 2:
        #walk
        eChoice = "walk"
        amount = r.randint(1,3) #miles
    elif x == 3:
        #cycle
        eChoice = "cycle"
        amount = r.randint(1,3) #miles
    else:
        #swim
        eChoice = "swim"
        amount = r.randint(5,10) #lengths of a pool


    exerciseLabel.configure(text="Name: " + eChoice)
    exerciseDescription.configure(text="Amount: " + str(amount))


myGUI = Tk() #create window

myGUI.title("Weight Loss Program") #title of the window
myGUI.configure(bg="deepskyblue") #background colour
exerciseButton = Button(myGUI, text="Generate Exercise", fg="mediumpurple", command=exercise) #create button that calls exercise function
exerciseButton.pack()
name = "Name: " + eChoice
exerciseLabel = Label(myGUI, text=name, fg="mediumpurple") #create label for exercise name
exerciseLabel.pack()
description = "Amount: " + amount
exerciseDescription = Label(myGUI, text=description, fg="mediumpurple") #create label for exercise name
exerciseDescription.pack()

myGUI.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...