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

Time:10-30

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()

CodePudding user response:

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()

CodePudding user response:

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()

CodePudding user response:

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()

CodePudding user response:

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!

  • Related