Python Tkinter:点击按钮后将函数内容显示在消息框而非终端
问题解决:让笑话同时显示在终端和Tkinter消息框里
你的代码有几个关键问题导致消息框为空,同时没正确获取笑话内容,修改方案如下:
问题点分析
- 缺少
tkinter核心模块导入:代码里用了tk.Tk()但没写import tkinter as tk,规范写法必须补上 - 错误赋值逻辑:
joke1 = print(pyjokes.get_joke())中,print()函数的返回值是None,所以joke1实际是空值,这就是消息框弹出空框的直接原因 - 消息框未传入内容:
messagebox.showinfo()需要指定标题和显示内容,否则默认弹出空框
修改后的完整代码
import pyjokes import tkinter as tk from tkinter import ttk from tkinter import messagebox def get_funny(): # 先获取笑话内容 joke1 = pyjokes.get_joke() # 打印到终端 print(joke1) # 显示在消息框,指定标题和消息内容 messagebox.showinfo(title="新鲜出炉的笑话", message=joke1) root = tk.Tk() root.title("Free Jokes") window_width = 300 window_height = 200 # 获取屏幕尺寸并计算窗口居中位置 screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() 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}") message = tk.Label(root, text="Fun Box 3000") message.pack() # 创建按钮 funny_button = ttk.Button( root, text="Click for funny", command=get_funny ) funny_button.pack( ipadx=5, ipady=5, expand=True ) root.mainloop()
关键修改说明
- 补上
import tkinter as tk,确保tk模块能正常调用 - 先调用
pyjokes.get_joke()获取笑话内容赋值给joke1,再单独执行print(joke1)输出到终端 - 调用
messagebox.showinfo()时传入title和message参数,把joke1作为消息内容传递进去,这样消息框就能正常显示笑话了
内容的提问来源于stack exchange,提问作者Hellboy
相关产品推荐
相关产品推荐

