【问题标题】:How to show buttons text in a calculator screen如何在计算器屏幕中显示按钮文本
【发布时间】:2016-08-04 08:29:08
【问题描述】:

我制作了一个简单的计算器,带有 1、2、3 等按钮......但我无法将 1 或 2 等按钮文本放到计算器屏幕上。 如果你们给我一些提示会很有帮助..

from tkinter import *
root = Tk()
buttons = '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-'

def calc(value):
    res = num.get()
    res = res + " " + value
    res = str(eval(res))
    num.set(res)


num = StringVar()
rows = 1
col = 0

ent = Entry(root, textvariable = num, background = "#D0F3F5", border = 2, width = 50)
ent.bind('<FocusOut>')
ent.grid(row = 0 , column = 0, columnspan = 4, ipadx = 5, ipady = 5)

Button(root, text = '=', width = 45, command = calc).grid(column = 0, row = 5, columnspan = 4)

for button in buttons:
    button = Button(root,width = 10, text = button, command = lambda: calc(button))
    #button.bind('<Button-1>', lambda e: screen(button))
    button.grid(row = rows, column = col, sticky = "W E")
    button['relief']="groove"
    col = col + 1

    if col == 4:
        rows = rows + 1
        col = 0

    if rows > 6:
        break




root.mainloop()

【问题讨论】:

  • 无法理解某些位的用途。 command = calc 这怎么用? for button in buttons: button = Button(..) 在这里使用相同的命名。 res + " " + valuestr(eval(res))你想评估什么?

标签: python tkinter


【解决方案1】:

这里有几个问题。

1) 变量button 用于两种不同的目的,其中一个会覆盖另一个。您需要重命名其中之一。

2) using lambdas with parameters in for loops 时,要获取该参数的当前值,需要显式写入该值。

3) 您没有将任何参数传递给等号按钮的命令。

4) 要进行计算,您需要检查按下的按钮是否为=。如果没有,你不应该尝试计算任何东西。

将所有这些应用到您的代码中会导致:

def calc(value):
    res = num.get()
    res = res + value

    if value == "=": 
        res = str(eval(res[:-1])) #to exclude equal sign itself

    num.set(res)

#equal sign button
Button(root, text = '=', width = 45, command = lambda: calc("=")).grid(...)

#for loop and renaming a variable
for x in buttons:
    button = Button(root,width = 10, text = x, command = lambda x=x: calc(x))

【讨论】:

  • 谢谢 @Lafexlos 先生 ..它现在正在工作 ..您真的帮助了我先生..现在我通过您的解释了解了 lambda 的目的。
  • @Ahmad 如果此答案解决了您的问题,请单击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
  • 我不知道否则我以前会这样做..再次感谢..:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
相关资源
最近更新 更多