Python3 Tkinter - 按钮通过浮动增加输入框值,例如 1.0,然后更新输入框显示

Python3 Tkinter - Button to increase entry box value by float such as 1.0 then update entry box display

我正在尝试创建一些按钮,将浮点值附加到 tkinter 输入框中的当前值。

from tkinter import *
import tkinter.ttk

menu = Tk()
menu.geometry('800x480')
frame1 = Frame(menu) 
frame1.grid()

#entry box
e1 = Entry(frame1)
e1.insert(0, float("1.0")) 
e1.grid(row=2, pady=5, ipadx=5, ipady=5)

#buttons
bt1 = Button(frame1, text="Add 1.0")
bt1.grid() 
bt2 = Button(frame1, text="Add 0.1")
bt2.grid()
bt3 = Button(frame1, text="Add 0.01")
bt3.grid()

例如,假设e1 中的当前值为1.0。我想创建一个按钮,将 1.0 添加到当前值(将其变为 2.0 并显示它而不是 1.0)。我还想制作添加值 0.1 和 0.01 的按钮。最好的方法是什么?目前我正在考虑使用计数器,但我不太确定如何实现它。

为了形象化我的意思以防万一我没有很好地解释它基本上我有当前的设置before the button is clicked. Suppose I click add 1.0 I want the 1.0 to turn into 2.0

您可以使用command=为按钮分配功能。此函数必须从 Entry 中获取文本,转换为 float,添加 0.1,(删除 Entry 中的所有文本),向 Entry 中插入新值,

import tkinter as tk

def add_1_0():
    value = float(e1.get())
    value += 1.0
    e1.delete(0, 'end')
    e1.insert(0, value)

def add_0_1():
    value = float(e1.get())
    value += 0.1
    e1.delete(0, 'end')
    e1.insert(0, value)

def add_0_01():
    value = float(e1.get())
    value += 0.01
    e1.delete(0, 'end')
    e1.insert(0, value)

root = tk.Tk()

#entry box
e1 = tk.Entry(root)
e1.insert(0, 1.0) 
e1.pack()

#buttons
bt1 = tk.Button(root, text="Add 1.0", command=add_1_0)
bt1.pack() 
bt2 = tk.Button(root, text="Add 0.1", command=add_0_1)
bt2.pack()
bt3 = tk.Button(root, text="Add 0.01", command=add_0_01)
bt3.pack()

root.mainloop()

您可以将重复的代码放在一个函数中

def add_1_0():
    add(1.0)

def add_0_1():
    add(0.1)

def add_0_01():
    add(0.01)

def add(val):
    value = float(e1.get())
    value += val
    e1.delete(0, 'end')
    e1.insert(0, value)

如果您在一个函数中有代码,那么您可以使用 lambda 为带参数的函数赋值。

import tkinter as tk

def add(val):
    value = float(e1.get())
    value += val
    e1.delete(0, 'end')
    e1.insert(0, value)

root = tk.Tk()

#entry box
e1 = tk.Entry(root)
e1.insert(0, 1.0) 
e1.pack()

#buttons
bt1 = tk.Button(root, text="Add 1.0", command=lambda:add(1.0))
bt1.pack() 
bt2 = tk.Button(root, text="Add 0.1", command=lambda:add(0.1))
bt2.pack()
bt3 = tk.Button(root, text="Add 0.01", command=lambda:add(0.01))
bt3.pack()

root.mainloop()