如何在python中的多个文本小部件中获取所选文本?

时间:2014-11-30 00:35:24

标签: python tkinter widget

我正在尝试编写一个小python tkinter应用程序,显示所选文本(使用鼠标)另一个标签。但我有多个文本小部件的问题。我怎么知道我使用哪个文本小部件?有10个文本小部件,当我从任何小部件中选择文本时,它应该显示标签。我在Windows 7上使用python 3.4.2。非常感谢。

#! python3
# -*- coding: utf8 -*-

from tkinter import *

class omniAnaliz(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.screen()

    def screen(self):
        self.t1 = Text(self, height=1, width=50)
        self.t1.pack(side='top')
        self.t1.insert(END, '1D D6 F8 F0 C3 08 04 00 62 63 64 65 66 67 68 69')
        self.t1.configure(state="disabled")

        self.t2 = Text(self, height=1, width=50)
        self.t2.pack(side='top')
        self.t2.insert(END, '30 F0 F8 D6 1D 64 64 01 00 71 1D 9F 00 1D 9F 00')
        self.t2.configure(state="disabled")

        # More text widget

        self.l1 = Label(self)
        self.l1.pack(side='top')

        self.t1.bind("<Button-3>", self.hex2dec)
        self.t2.bind("<Button-3>", self.hex2dec)

    def hex2dec(self, event):
        self.l1.config(text=self.t1.get(SEL_FIRST, SEL_LAST))

if __name__ == '__main__':
    root = Tk()
    omniAnaliz(root).pack()
    root.mainloop()

1 个答案:

答案 0 :(得分:1)

通常,您将每个窗口小部件的Tkinter ID存储在列表中,并将其偏移量传递给该函数。我更喜欢StringVar来设置标签的set(),但这是个人偏好。

from tkinter import *
from functools import partial

class omniAnaliz(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.text_vars=[]  ## text widget id's
        self.screen()

    def screen(self):
        ctr=0
        for txt in ['1D D6 F8 F0 C3 08 04 00 62 63 64 65 66 67 68 69',
                '30 F0 F8 D6 1D 64 64 01 00 71 1D 9F 00 1D 9F 00',
                'a, b, c, 1, 2, 4']:
            t = Text(self, height=1, width=50)
            t.pack(side="bottom")
            t.insert(END, txt)
            t.configure(state="disabled")
            t.bind("<Button-3>", partial(self.hex2dec, ctr))
            ## first ID is item[0], 2nd text widget is item[1], etc.
            self.text_vars.append(t)
            ctr += 1

        self.label_text=StringVar()
        self.label_text.set("Nothing yet")
        self.l1 = Label(self, textvariable=self.label_text)
        self.l1.pack(side='top')

    def hex2dec(self, widget_num, event):
        this_text_widget=self.text_vars[widget_num]
        self.label_text.set(this_text_widget.get(SEL_FIRST, SEL_LAST))

root = Tk()
omniAnaliz(root).pack()
root.mainloop()