在python 2.7中,我想根据给定的用户输入打印一个地方的价格。每当用户输入不同数量的人时,价格就会有所不同。
from Tkinter import *
top = Tk()
top.geometry("500x500")
a = Label(text="Adult:")
a.place(x=50,y=100)
adult_input = Entry(top)
adult_input.place(x=100,y=100)
adult_num = Label (text="x RM 5.00 per pax :")
adult_num.place(x=250,y=100)
top.mainloop()
我应该如何根据用户输入打印价格?
答案 0 :(得分:0)
这是适合您情况的最简单的解决方案。在top.mainloop()
之前添加以下行:
b = Button(top,
text="Confirm",
command=lambda: adult_num.config(text=adult_input.get()))
b.place('''anywhere''')
点击按钮时,这会更新您的adult_num
标签。
如果这还不够,你需要在显示之前计算一个值,那么你需要一个函数。
假设您有f
函数:
def f(adults_number):
adults_number = int(adults_number)
return '''the result of some formula'''
然后你必须在按钮的command
:
b = Button(top,
text="Confirm",
command=lambda: adult_num.config(text=str(f(adult_input.get()))))
此外,您的adult_num
标签应附加到top
,因此声明应为:
adult_num = Label(top, text="...")
答案 1 :(得分:0)
您可以使用Button
执行将计算值的函数
import Tkinter as tk
# --- functions ---
def recalc():
value = e.get()
if value != '':
l['text'] = float(value) * 5.00
# --- main ---
root = tk.Tk()
e = tk.Entry(root)
e.pack()
e.bind('<KeyRelease>', recalc)
l = tk.Label(root)
l.pack()
b = tk.Button(root, text="Recalc", command=recalc)
b.pack()
root.mainloop()
或者您可以将事件绑定到Entry
,并在每个键之后计算它。
import Tkinter as tk
# --- functions ---
def recalc(event): # bind executes function with argument `event`
#value = e.get()
value = event.widget.get()
if value != '':
l['text'] = float(value) * 5.00
# --- main ---
root = tk.Tk()
e = tk.Entry(root)
e.pack()
e.bind('<KeyRelease>', recalc)
l = tk.Label(root)
l.pack()
root.mainloop()