2016-08-04 7 views
-2

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() 
+0

にあなたのコードの結果に、これらすべてを適用します。 'command = calc'これはどのように使用されますか? 'for button in button:button = Button(..)'ここでは同じ名前を使用します。 'res +" "+ value" 'str(eval(res))'あなたは何を評価しようとしていますか? –

答えて

0

は、ここでいくつの問題があります。

1)変数buttonは、2つの異なる目的のために使用され、その一方が他方を無効にします。それらの名前の1つをリネームする必要があります。

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)) 
+0

ありがとうございました。@ Lafexlos。それは今働いています。あなたは本当に私を助けました。そして今、私はラムダの目的をあなたの解説と共に理解しました。 – Ahmad

+0

@Ahmadこの回答があなたの質問を解決した場合、チェックマークをクリックして[受諾](http://meta.stackexchange.com/q/5234/179419)を検討してください。これは、あなたが解決策を見つけ出し、回答者とあなた自身の両方に評判を与えていることを広範なコミュニティに示します。これを行う義務はありません。 – Lafexlos

+1

私はそうでなければ私は前にそれをしていただろうか分からなかった..再びありがとう:) – Ahmad

関連する問題