pythontkinterbutton

Returning text from a function when clicking a button Python Tkinter


I'm working on an exercise and I'm learning how to use Tkinter.

I manage to get my code working but I can't figure out a way of making it work the way I want.

I want the joke to be printed and then appended to the messagebox, rather than having it displayed in the terminal.

Any pointers? Couldn't find an answer in the similar questions asked.

I've tried using the variable inside the messagebox but it just opens an empty box.

import pyjokes
from tkinter import ttk
from tkinter import messagebox
def get_funny():
    joke1 = print(pyjokes.get_joke())
    messagebox.showinfo()

root = tk.Tk()
title = root.title("Free Jokes")
window_width = 300
window_height = 200
#get screen dimensions
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#find the center point
center_x = int(screen_width/2 - window_width / 2)
center_y = int(screen_height/2 - window_height / 2)

root.geometry(f"{window_width}x{window_height}+{center_x}+{center_y}")
#root.resizable(False,False) make the window a fixed size
message = tk.Label(root, text="Fun Box 3000")
message.pack()

#Button
funny_button = ttk.Button(
    root,
    text="Click for funny",
    command=get_funny
)

funny_button.pack(
    ipadx=5,
    ipady=5,
    expand=True
)

root.mainloop()```

Solution

  • You should pass it in showinfo:

    def get_funny():
        joke = pyjokes.get_joke()
        messagebox.showinfo("Joke", joke)