【问题标题】:How to update Label widget each time Button is clicked using TkInter - Python每次使用 TkInter 单击按钮时如何更新标签小部件 - Python
【发布时间】:2023-03-06 13:37:02
【问题描述】:

所以我正在尝试构建一个简单的计算器,它在标签中显示数字 pi,即 3.14,并且每次单击“点击我”按钮时,它都会添加另一个十进制值3.14。例如,一旦点击Label会显示3.141,第二次:3.1415等等。

代码如下:

# Import the Tkinter functions
from Tkinter import *


# Create a window
loan_window = Tk()

loan_window.geometry('{}x{}'.format(500, 100))

# Give the window a title
loan_window.title('Screeen!')

## create the counter
pi_num = 3.14

# NUMBER frame
frame = Frame(loan_window, width=100, height=50)
frame.pack()

def addPlaceValue():

    pi_num= 3.14
    return pi_num


## create a label and add it onto the frame
display_nums = Label(frame, text = 'pi_num')
display_nums.pack()


#### create a label and add it onto the frame
##display_nums = Label(frame, text = pi_num)
##display_nums.pack()
##

# Create a button which starts the calculation when pressed
b1 = Button(loan_window, text = 'Click me', command= addPlaceValue, takefocus = False)
b1.pack()



# Bind it 
loan_window.bind('<Return>', addPlaceValue())


# event loop
loan_window.mainloop()

我曾多次尝试跟踪按钮点击,但均未成功。我看到一个问题;代码不知道第 n 次单击按钮。有什么想法吗?

【问题讨论】:

    标签: python user-interface button tkinter tkinter-canvas


    【解决方案1】:

    我不知道您如何将 pi 存储为位数......但是,这是一种非常容易指定精度的方法(假设精度为 100):

    from sympy import mpmath
    mpmath.dps = 100 #number of digits
    PI = str(mpmath.pi)
    

    PI 是一个常量实例,不能自然下标,因此我们将其转换为 str 以供以后索引。

    现在,至于更新文本,我们可以在每次放置按钮时跟踪计数器。

    我们可以将此计数器设置为loan_window 的属性,默认为4 以显示pi 的最常见表示3.14,然后递增和更改标签文本:

    编辑:绑定时你也想只传递函数名而不是 function_name() 这实际上是调用函数

    import sympy, Tkinter as tk
    
    sympy.mpmath.dps = 100
    PI = str(sympy.mpmath.pi)
    
    loan_window = tk.Tk()
    loan_window.counter = 4
    
    frame = tk.Frame(loan_window, width=100, height=50)
    frame.pack()
    
    def addPlaceValue():
    
        loan_window.counter += 1
        display_nums['text'] = PI[:loan_window.counter]
    
    display_nums = tk.Label(frame, text = PI[:loan_window.counter])
    display_nums.pack()
    
    b1 = tk.Button(loan_window, text = 'Click me', command= addPlaceValue, takefocus = False)
    b1.pack()
    
    loan_window.bind('<Return>', addPlaceValue)
    loan_window.mainloop()
    

    【讨论】:

    • 我认为,当函数没有event 参数时,这会在尝试使用绑定时返回一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多