Python3 Tkinter按钮增加输入框的值,如1.0,然后更新输入框显示

2024-04-26 02:49:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建几个按钮,在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。假设我单击add1.0我想要the 1.0 to turn into 2.0。在


Tags: thetextimportaddtkinterbutton按钮grid
1条回答
网友
1楼 · 发布于 2024-04-26 02:49:58

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

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

^{pr2}$

如果在一个函数中有代码,则可以使用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()

相关问题 更多 >