9
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.

nbro
  • 15,395
  • 32
  • 113
  • 196
Lilluda 5
  • 1,111
  • 3
  • 18
  • 38

1 Answers1

12

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()
Charles Brunet
  • 21,797
  • 24
  • 83
  • 124
  • 1
    while it doesn't really matter in this specific example, when you get the text you should use an index of "end-1c". The text widget always guarantees a newline at the end which you typically don't want when getting the text since it's not part of what the user typed in. – Bryan Oakley Apr 06 '11 at 13:40