tkinter,如何获取 Entry 小部件的值? [英] tkinter, how to get the value of an Entry widget?

查看:783
本文介绍了tkinter,如何获取 Entry 小部件的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果利润率具有特定值 (.23),我正在尝试为用户提供计算其预计销售额的利润的可能性.用户应该能够输入任何值作为预计销售额:

I'm trying to offer the user the possibility to calculate his profit of his projected sales if the margin has a certain value (.23). The user should be able to enter any value as projected sales:

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

推荐答案

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

You can get what's inside Entry widget using get method like:

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

这是一个可以满足您要求的示例:

Here's an example that does around what you want:

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() 类来同步多个小部件的整数文本,例如:

You may also want to use textvariable option and tkinter.IntVar() class for synchronizing integer texts for multiple widgets like:

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

以上示例显示 labelProSalesentrytext 值始终相等,因为它们使用相同的变量 projectedSales,作为他们的 textvariable 选项.

Above example shows that labelProSales and entry have their text values equal at all times, as both use the same variable, projectedSales, as their textvariable option.

这篇关于tkinter,如何获取 Entry 小部件的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆