[英]How to read text from a Tkinter Text Widget
from Tkinter import *
window = Tk()
frame=Frame(window)
frame.pack()
text_area = Text(frame)
text_area.pack()
text1 = text_area.get('0.0',END)
def cipher(data):
As,Ts,Cs,Gs, = 0,0,0,0
for x in data:
if 'A' == x:
As+=1
elif x == 'T':
Ts+=1
elif x =='C':
Cs+=1
elif x == 'G':
Gs+=1
result = StringVar()
result.set('Num As: '+str(As)+' Num of Ts: '+str(Ts)+' Num Cs: '+str(Cs)+' Num Gs: '+str(Gs))
label=Label(window,textvariable=result)
label.pack()
button=Button(window,text="Count", command= cipher(text1))
button.pack()
window.mainloop()
我想要完成的是在我的Text小部件中輸入一串'AAAATTTCA'並讓標簽返回出現的次數。 使用條目'ATC',函數將返回Num As:1 Num Ts:1 Num Cs:1 Num Gs:0。
我不明白的是為什么我沒有正確閱讀我的text_area。
我認為你誤解了Python和Tkinter的一些概念。
創建Button時,命令應該是對函數的引用,即不帶()的函數名。 實際上,在創建按鈕時,您只需調用一次密碼函數。 您不能將參數傳遞給該函數。 您需要使用全局變量(或更好,將其封裝到類中)。
如果要修改Label,只需設置StringVar即可。 實際上,每次調用密碼時,您的代碼都會創建一個新標簽。
有關工作示例,請參閱下面的代碼:
from Tkinter import *
def cipher():
data = text_area.get("1.0",END)
As,Ts,Cs,Gs, = 0,0,0,0
for x in data:
if 'A' == x:
As+=1
elif x == 'T':
Ts+=1
elif x =='C':
Cs+=1
elif x == 'G':
Gs+=1
result.set('Num As: '+str(As)+' Num of Ts: '+str(Ts)+' Num Cs: '+str(Cs)+' Num Gs: '+str(Gs))
window = Tk()
frame=Frame(window)
frame.pack()
text_area = Text(frame)
text_area.pack()
result = StringVar()
result.set('Num As: 0 Num of Ts: 0 Num Cs: 0 Num Gs: 0')
label=Label(window,textvariable=result)
label.pack()
button=Button(window,text="Count", command=cipher)
button.pack()
window.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.