How to read text from a Tkinter Text Widget

一曲冷凌霜 提交于 2019-12-04 19:33:44

问题


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

What I'm trying to accomplish is entering a string of 'AAAATTTCA' in my Text widget and have the label return the number of occurrences. With the entry 'ATC' the function would return Num As: 1 Num Ts: 1 Num Cs: 1 Num Gs: 0.

What I don't understand is why I am not reading in my text_area correctly.


回答1:


I think you misunderstand some concepts of Python an Tkinter.

When you create the Button, command should be a reference to a function, i.e. the function name without the (). Actually, you call the cipher function once, at the creation of the button. You cannot pass arguments to that function. You need to use global variables (or better, to encapsulate this into a class).

When you want to modify the Label, you only need to set the StringVar. Actually, your code creates a new label each time cipher is called.

See code below for a working example:

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


来源:https://stackoverflow.com/questions/5560828/how-to-read-text-from-a-tkinter-text-widget

标签

工具导航Map