How do I get a selected string in from a Tkinter text box?

前端 未结 3 1389
Happy的楠姐
Happy的楠姐 2020-12-09 11:42

I\'d like to be able to get a string out of a highlighted portion of text, how do I go about this?

3条回答
  •  一生所求
    2020-12-09 12:09

    use the get method. If you want the selected text use the indices SEL_FIRST and SEL_LAST.

    [edit]] one of the comments speculated this didn't work with Tkinter because there was no attribute "sel". "sel" isn't an attribute, it's a tag. Tags are a remarkably powerful feature of the text widget.

    Here's an example:

    import Tkinter as tk
    import tkFont
    
    class App:
        def __init__(self):
            root=tk.Tk()
            self.text = tk.Text(root)
            self.text.pack()
            self.button = tk.Button(root, text="Get Selection", command=self.OnButton)
            self.button.pack()
            root.mainloop()
    
        def OnButton(self):
            print "selected text: '%s'" % self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
    
    
    app=App()
    

    For this demo to work, type some text in the text box then press the button.

提交回复
热议问题