tkinter, как получить значение виджета Entry?

Я пытаюсь предложить пользователю возможность рассчитать прибыль от его прогнозируемых продаж, если маржа имеет определенное значение (0,23). Пользователь должен иметь возможность вводить любое значение в качестве прогнозируемых продаж:

from tkinter import *

root = Tk()

margin = 0.23
projectedSales = #value of entry
profit = margin * int(projectedSales)

#My function that is linked to the event of my button
def profit_calculator(event):
    print(profit)


#the structure of the window
label_pan = Label(root, text="Projected annual sales:")
label_profit = Label(root, text="Projected profit")
label_result = Label(root, text=(profit), fg="red")

entry = Entry(root)

button_calc = Button(root, text= "Calculate", command=profit_calculator)
button_calc.bind("<Button-1>", profit_calculator)

#position of the elements on the window
label_pan.grid(row=0)
entry.grid(row=0, column=1)
button_calc.grid(row=1)              
label_profit.grid(row=2)
label_result.grid(row=2, column=1)

root.mainloop()

person Pak    schedule 19.11.2017    source источник
comment
Первоначальный вопрос включал также вопрос о том, как использовать текст ввода в качестве переменной.   -  person Nae    schedule 20.11.2017


Ответы (1)


Вы можете получить то, что находится внутри виджета Entry, используя метод get, например:

entry = tkinter.Entry(root)
entryString = entry.get()

Вот пример, который делает то, что вы хотите:

import tkinter as tk

root = tk.Tk()

margin = 0.23

entry = tk.Entry(root)

entry.pack()

def profit_calculator():
    profit = margin * int(entry.get())
    print(profit)

button_calc = tk.Button(root, text="Calculate", command=profit_calculator)
button_calc.pack()

root.mainloop()

Вы также можете использовать параметр textvariable и класс tkinter.IntVar() для синхронизации целочисленных текстов для нескольких виджетов, например:

import tkinter as tk

root = tk.Tk()

margin = 0.23
projectedSales = tk.IntVar()
profit = tk.IntVar()

entry = tk.Entry(root, textvariable=projectedSales)

entry.pack()

def profit_calculator():
    profit.set(margin * projectedSales.get())

labelProSales = tk.Label(root, textvariable=projectedSales)
labelProSales.pack()

labelProfit = tk.Label(root, textvariable=profit)
labelProfit.pack()

button_calc = tk.Button(root, text="Calculate", command=profit_calculator)
button_calc.pack()

root.mainloop()

Пример выше показывает, что labelProSales и entry всегда имеют одинаковые значения text, так как оба используют одну и ту же переменную projectedSales в качестве опции textvariable.

person Nae    schedule 19.11.2017
comment
Хорошо, большое спасибо за ваш ответ, я надеялся на такой ответ. Кажется, я начинаю понимать! - person Pak; 20.11.2017
comment
Извините, но здесь написано как ошибка: - person ; 29.08.2020
comment
@TroyD Эта ошибка не связана с фрагментом кода выше, поскольку переменная inputS не вообще упоминается. Для получения дополнительной помощи по этой ошибке я бы посоветовал прочитать ericlippert.com/2014/03/05/how-to-debug-small-programs - person Nae; 31.08.2020