-1

I'm new to tkinter so sorry if the solution is obvious. In tkinter I made a button. And I made a def`myClick: for something to happen when the button is pressed. But nothing happens after the button is pressed.

from tkinter import *
root = Tk()
def myClick():
    myLabel1 = Label(root, text="you clicked me")
    myLabel1.pack
myButton = Button(root, text="click me!", padx=50, command=myClick())
myButton.grid(row=1, column=1)
root.mainloop()
Tgsadman
  • 38
  • 1
  • 6

2 Answers2

2

I found a few problems. Here's my version which might be of help to you:

  1. You had command=myClick() but it should be command=myClick instead (without parentheses). If you have parentheses, it invokes the function once when it first loads your code. But if you pass it without parentheses, then it will be invoked every time you click the button. You can read more on this topic here.

  2. You had myLabel1.pack but it should be myLabel1.pack(). Here you didn't put parentheses so you didn't actually invoke the function. That's a part why nothing was happening.

  3. I changed myButton.grid(row=1, column=1) to myButton.pack() because there seemed to be some problem with mixing grid() and pack() methods. I'm new to tkinter myself, so there might be a simple solution for using both. But for the time being I changed it.

from tkinter import *
root = Tk()
def myClick():
    print("hello")
    myLabel1 = Label(root, text="you clicked me")
    myLabel1.pack()
myButton = Button(root, text="click me!", padx=50, command=myClick)
myButton.pack()
root.mainloop()
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
Pinusar
  • 21
  • 3
0

From: Python 3, Tkinter, How to update button text

You can use the text variable option of the Button class. The code could be the following:

from tkinter import *
root = Tk()
def myClick():
    print("Click")
    bot_text.set("you clicked me")
    myButton.text="you clicked me"

bot_text = StringVar()
myButton = Button(root, textvariable=bot_text, padx=50, command=myClick)
bot_text.set("Click me!")
myButton.grid(row=1, column=1)
myButton.pack()
root.mainloop()
AarónRF
  • 31
  • 2