[英]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.