Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter - editing a text box using a button

Using Tkinter in Python I am trying to change what is displayed in a textbox when a button is pressed. My code so far is:

screen = Tk()
text = Text(screen, height = 2, width = 30)
text.pack()
text.insert(END, '-')

def apress():
    text.insert(END, 'a')

a = Tkinter.Button (screen, text = 'a', width = 5, command = apress).pack()

mainloop()

When the code is run nothing happens and the debugger will not stop running even if you click 'abort debugging'. Is there a way to fix this?

like image 384
T. Green Avatar asked Aug 01 '26 20:08

T. Green


1 Answers

Here's the working code:

from Tkinter import *

screen = Tk()
text = Text(screen, height = 2, width = 30)
text.pack()
text.insert(END, '-')

def apress():
    text.insert(END, 'a')

btn = Button(screen, text = 'a', width = 5, command = apress) 
btn.pack()

mainloop()

Changes I made:

  • Added the import from Tkinter import *
  • Used Button instead of Tkinter.Button - since we used an wildcard import
  • Button.pack() separated on a new line

Demo:

Initial view: Before clicking button

Clicked the button several times:

After clicking button

like image 63
masnun Avatar answered Aug 06 '26 10:08

masnun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!