How do you set functions for a button, on Tkinter?

Question:

my function wont carry out for the button assigned. Im using visual studio code. For the
def myClick():
myLabel =Label(window, text …, command…

it wont occur. on visual studio code, the ‘myLabel’ greys out and has the error ‘is not accessedPylance’

# add response to input


def myClick():
    myLabel = Label(window, text="Hello" + e.get() + "...      ")
myLabel.pack

# create button
myButton = Button(window, text="next", command=myClick, fg="black")
myButton.pack()
Asked By: caterin

||

Answers:

I think its just that you are not calling pack(). When I fix that I see the label appear:

def myClick():
    myLabel = Label(window, text="Hello" + e.get() + "...      ")
    myLabel.pack()
Answered By: quamrana

I think you should pack myLabel inside the function, and add "()" at the end:

def myClick():
    myLabel = Label(window, text="Hello" + e.get() + "...      ")
    myLabel.pack()

# create button
myButton = Button(window, text="next", command=myClick, fg="black")
myButton.pack()
Answered By: Jan Niedospial

I see two problems with your code.
Firstly, myLabel.pack() is not aligned as myLabel.
You have to call the pack() method in the myClick() function.

Secondly, dont forget to use the brackets for calling the pack() method on myLabel.

You can see a working example down here.

from tkinter import *

window = Tk()

def myClick():
    myLabel = Label(window, text="Hello")
    myLabel.pack() # put this into the same level as myLabel

# create button
myButton = Button(window, text="next", command=myClick, fg="black")
myButton.pack()

window.mainloop()
Answered By: lambdaxpy

You are not calling the pack function. You wrote myLabel.pack without the brackets – () – so Python does not recognize it as a function.

Your code, improved:

# add response to input


def myClick():
    myLabel = Label(window, text="Hello" + e.get() + "...      ")
    myLabel.pack()

# create button
myButton = Button(window, text="next", command=myClick, fg="black")
myButton.pack()

Thanks for asking, keep up great work!

Answered By: stysan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.