简体   繁体   English

如何从 tkinter 调用消息框?

[英]How to call messagebox from tkinter?

I'm creating a Tkinter-based GUI in Python and I have a problem: messagebox does not appear when I'm getting data from the Entry widget.我正在用 Python 创建一个基于 Tkinter 的 GUI,但我遇到了一个问题:当我从 Entry 小部件获取数据时没有出现消息框。 How can I solve it?我该如何解决?

from tkinter import *
import random


win = Tk()
win.title("Sample")
win.resizable(False, False)
win.configure(bg="#767676")

def game():
    entry = Entry_field.get()
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"]
    randomise = random.choice(days)
    messagebox.showinfo("Ответ", randomise)

Label_field = Label(win, text="Choose your day!", font=("outrun", 10, "bold"))
Label_field.grid(row=0, column=0)

Notification_Label = Label(win, text="Enter your name here", font=("montserrat", 10, "bold"), bg="#EF9A9A")
Notification_Label.grid(row=1, column=0, sticky=W)

Entry_field = Entry(win, width=30)
Entry_field.grid(row=1, column=1)

Button_field = Button(win, text="Press", command=game)
Button_field.grid(row=1, column=2)

win.mainloop()

You are trying to use the showinfo function from the tkinter.messagebox module, but haven't imported it.您正在尝试使用tkinter.messagebox模块中的showinfo函数,但尚未导入它。 You need to add import tkinter.messagebox as messagebox or from tkinter import messagebox line to the top of your code.您需要将import tkinter.messagebox as messageboxfrom tkinter import messagebox import tkinter.messagebox as messagebox from tkinter import messagebox行添加到代码的顶部。 Here is the full fixed code:这是完整的固定代码:

from tkinter import *
import tkinter.messagebox as messagebox
import random


win = Tk()
win.title("Sample")
win.resizable(False, False)
win.configure(bg="#767676")

def game():
    entry = Entry_field.get()
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"]
    randomise = random.choice(days)
    messagebox.showinfo("Ответ", randomise)

Label_field = Label(win, text="Choose your day!", font=("outrun", 10, "bold"))
Label_field.grid(row=0, column=0)

Notification_Label = Label(win, text="Enter your name here", font=("montserrat", 10, "bold"), bg="#EF9A9A")
Notification_Label.grid(row=1, column=0, sticky=W)

Entry_field = Entry(win, width=30)
Entry_field.grid(row=1, column=1)

Button_field = Button(win, text="Press", command=game)
Button_field.grid(row=1, column=2)

win.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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