【问题标题】:tkinter, how to get the value of an Entry widget? [duplicate]tkinter,如何获取 Entry 小部件的值? [复制]
【发布时间】:2018-05-02 21:17:34
【问题描述】:

如果保证金具有特定值 (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()

【问题讨论】:

  • 最初的问题确实还包括如何使用条目文本作为变量。

标签: python-3.x user-interface tkinter


【解决方案1】:

您可以使用 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()

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

【讨论】:

  • 好的,非常感谢您的回答,我很期待这种回答。我想我开始明白了!
  • 抱歉,这里显示为错误:
  • File "interface.py", line 6, in search entryString = inputS.get() AttributeError: 'NoneType' object has no attribute 'get'
  • @TroyD 该错误与上面的代码片段无关,因为根本没有提到inputS 变量。有关该错误的进一步帮助,我建议阅读ericlippert.com/2014/03/05/how-to-debug-small-programs
猜你喜欢
  • 1970-01-01
  • 2012-02-16
  • 2012-04-06
  • 2019-02-26
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多