简体   繁体   中英

Why is Tkinter not displaying Button?

import Tkinter as ass
root = ass.Tk()
frame = ass.Frame(root)
button1 = ass.Button(frame, command=button1(), text='Kushagra', width=50, height=40)
button1.pack(side=ass.LEFT)
root.mainloop()

button1() is a function I made which i don't think is relevant. After I run this all I get is a blank window. How do I fix this?

You didn't pack the frame widget after creating the frame. The below is the edited code

import tkinter as ass
root = ass.Tk()
frame = ass.Frame(root)
frame.pack()
button1 = ass.Button(frame, text="QUIT")
button1.pack(side=ass.LEFT)
root.mainloop()

You have to pack the frame if you want it to be displayed. This will let the button to be shown but the function button1() won't work as you want because it would be called when it is given to the Button as a command , As you have used parenthesis () after giving it to the button as a command . You just need to remove those parentheses.

Like this:

import tkinter as ass


def button1():
    return


root = ass.Tk()
frame = ass.Frame(root)
frame.pack()
button1 = ass.Button(frame, command=button1, text='Kushagra', width=50, height=40)
button1.pack(side=ass.LEFT)
root.mainloop()

And if you need to pass arguments to any function then you should use lambda before giving it as a command to any Button .

Like this:

import tkinter as ass


def test(a):
    print(a)


root = ass.Tk()
frame = ass.Frame(root)
frame.pack()
button1 = ass.Button(frame, command=lambda: test(1), text='Kushagra', width=50, height=40)
button1.pack(side=ass.LEFT)
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM