Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read text from a Tkinter Text Widget

Tags:

python

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

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.

like image 892
Lilluda 5 Avatar asked Apr 06 '11 02:04

Lilluda 5


People also ask

How do I get text from a text widget?

We can get the input from the user in a text widget using the . get() method. We need to specify the input range which will be initially from 1.0 to END that shows the characters starting and ending till the END.


1 Answers

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()
like image 103
Charles Brunet Avatar answered Oct 30 '22 23:10

Charles Brunet