Search code examples
pythontkintertkinter-layouttkinter-text

Disable mouse press on Tkinter Text Widget


Background I have created a tk.Text widget within a frame and used grid to place successfully within my tool. I use methods to run read commands and display the results within the tk.Text widget. I only want the tk.Text to display the results nothing else and this works as expected.

resultsbox = tk.Text(centerframe)
resultsbox.config(state='disabled', bd='10', height=38, width=92, bg='black', fg='green', font='fixedsys')
resultsbox.grid(row=0, column=1, sticky="e")

I use the following commands on each method to enable my write results and then disable the user from typing into the tk.Text widget:

Example

resultsbox.config(state='normal')
resultsbox.insert(tk.INSERT, RESULT1, 'standard', "\n\n")
resultsbox.config(state='disabled')

This again works as expected.

Issue The problem i have is if a user clicks within the tk.Text widget even though it is disabled the next result that the tool writes to the widget will place it at the point where the user last clicked causing a very unreadable result.

Example This Screenshot shows if a user has clicked within the widget and then the next result is written.

Summary Is it possible to stop the user pressing within the tk.Text widget?


Solution

  • You don't have to disable your mouse keys. It is very simple. You just replace tk.INSERT with tk.END. This tells where to insert. Either at the marked position or at the end. Check out my example. I created 2 buttons, one with tk.INSERT and one with tk.END.

    import tkinter as tk
    
    
    def insert_END():
        RESULT1 = '---OUTPUT---'
        resultsbox.config(state='normal')
        resultsbox.insert(tk.END, RESULT1, 'standard', "\n\n")
        resultsbox.config(state='disabled')
    
    
    def insert_INSERT():
        RESULT1 = '---OUTPUT---'
        resultsbox.config(state='normal')
        resultsbox.insert(tk.INSERT, RESULT1, 'standard', "\n\n")
        resultsbox.config(state='disabled')
    
    
    root = tk.Tk()
    root.geometry("1000x1000")
    frame1 = tk.Frame(root).grid(row=1, column=1)
    
    resultsbox = tk.Text(frame1)
    resultsbox.config(state='disabled', bd='10', height=38, width=92, bg='black', fg='green', font='fixedsys')
    resultsbox.grid(row=0, rowspan=2, column=1, sticky="e")
    
    btn1 = tk.Button(master=frame1, text='END', command=insert_END)
    btn1.grid(row=0, column=0, padx=30)
    
    btn2 = tk.Button(master=frame1, text='INSERT', command=insert_INSERT)
    btn2.grid(row=1, column=0, padx=30)
    
    root.mainloop()