tkinter,如何获取Entry小部件的值?

14

我正在尝试为用户提供一种可能性,即在利润率为某个特定值(.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()

最初的问题确实包括如何将Entry文本用作变量。 - Nae
1个回答

23

您可以使用get方法获取Entry小部件中的内容,例如:

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

上面的例子表明,labelProSalesentry始终具有相同的text值,因为它们都使用同一变量projectedSales作为它们的textvariable选项。

1
好的,非常感谢您的回答,我一直期待这样的答案。我觉得我开始理解了! - Pak
抱歉,这里显示为错误: - user13566917
entryString = inputS.get() AttributeError: 'NoneType' object has no attribute 'get'``` - user13566917
@TroyD,那个错误与上面的代码片段无关,因为根本没有提到inputS变量。如果需要进一步帮助解决该错误,我建议阅读https://ericlippert.com/2014/03/05/how-to-debug-small-programs/。 - Nae

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接