如何从 Tkinter 文本小部件读取文本 [英] How to read text from a Tkinter Text Widget

查看:30
本文介绍了如何从 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"后,函数将返回 Num As: 1 Num Ts: 1 Num Cs: 1 Num Gs: 0.

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.

我不明白的是为什么我没有在我的 text_area 中正确阅读.

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

推荐答案

我想你误解了 Python 和 Tkinter 的一些概念.

I think you misunderstand some concepts of Python an Tkinter.

当您创建按钮时,命令应该是对函数的引用,即不带 () 的函数名.实际上,您在创建按钮时调用了 cipher 函数一次.您不能将参数传递给该函数.您需要使用全局变量(或者更好,将其封装到一个类中).

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

当要修改Label时,只需要设置StringVar即可.实际上,每次调用 cipher 时,您的代码都会创建一个新标签.

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

这篇关于如何从 Tkinter 文本小部件读取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆