如何从Tkinter文本控件读取文本
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()
我想要实现的功能是,在我的文本框里输入一个字符串,比如'AAAATTTCA',然后标签会显示每个字母出现的次数。如果我输入'ATC',这个功能应该返回:字母A出现了1次,字母T出现了1次,字母C出现了1次,字母G出现了0次。
我不明白的是,为什么我没有正确读取我的文本区域。
1 个回答
12
我觉得你对Python和Tkinter的一些概念有些误解。
当你创建按钮时,命令(command)应该是一个函数的引用,也就是说,只需要写函数名,不要加括号(())。实际上,你在创建按钮的时候就已经调用了一次cipher函数。这样的话,你就不能给这个函数传递参数。你需要使用全局变量(或者更好的方法是把它封装到一个类里面)。
当你想修改标签(Label)时,只需要设置StringVar就可以了。实际上,你的代码每次调用cipher时都会创建一个新的标签。
下面的代码是一个可以正常工作的例子:
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()