简体   繁体   中英

How can I display output from a button command in a new window using tkinter?

I have successfully created a GUI that takes user input and gives the desired output, but I can't seem to figure out how to display this output in another window instead of just in the IDE console. My goal is to have a window pop up with the output once the user clicks 'Compute BMI', but as of right now, the output only shows in the console. I have looked for solutions but I can't seem to figure out what tools I can use to make this happen. I am new to GUIs so any help would be much appreciated.

from tkinter import *

root = Tk()

def myBMI():
    weight = float(Entry.get(weight_field))
    height = float(Entry.get(height_field))
    bmi = (weight*703)/(height*height)
    print(bmi)

height_label = Label(root, text="Enter your height: ")
height_field = Entry(root)
height_field.grid(row=0, column=1)
height_label.grid(row=0, sticky=E)

weight_label = Label(root, text="Enter your weight: ")
weight_field = Entry(root)
weight_field.grid(row=1, column=1)
weight_label.grid(row=1, sticky=E)

compute_bmi = Button(root, text="Compute BMI", command=myBMI)
compute_bmi.grid(row=2)

root.mainloop()

tkinter "pop-ups" should typically be handled via the tk.TopLevel() method! This will generate a new window that can be titled or have buttons put in it like:

top = Toplevel()
top.title("About this application...")

msg = Message(top, text=about_message)
msg.pack()

button = Button(top, text="Dismiss", command=top.destroy)
button.pack()

So instead of print(bmi) you could do something like, say:

top = tk.Toplevel()
msg = tk.Label(top, text=bmi)
msg.pack()

More documentation can be found at http://effbot.org/tkinterbook/toplevel.htm !

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