2016-05-08 140 views
0

所以我想建立一個簡單的計算器顯示的數字PI即標籤3.14每一次按鍵「點擊我」被點擊它爲3.14添加了另一個十進制值。例如,一旦點擊該標籤將顯示3.141,第二次:3.1415等等等等如何更新標籤控件使用Tkinter的點擊每次按鈕 - Python的

下面是代碼:

# 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() 

我試過很多次跟蹤按鈕點擊,但沒有這樣做。我看到一個問題;代碼不知道單擊哪一次按鈕。有任何想法嗎?

回答

0

我不知道你怎麼會有pi存儲位數....但是,這裏有一個方法非常容易地指定精度(假設100精度):

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

PI是一個常量實例,並不是自然可以下載的,所以我們將其轉換爲str以供以後編制索引。

現在,至於更新文本,我們可以在每次放置按鈕時跟蹤計數器。

我們可以在這個櫃檯爲屬性設置爲loan_window4默認顯示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() 
相關問題