我想在弹出窗口中打印输出?我应该如何处理?

时间:2019-12-21 04:02:26

标签: python python-3.x button tkinter popupwindow

import tkinter as tk
import datetime 

def write_slogan():
    dt_object = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print("OrderName: %s"%dt_object)


master = tk.Tk()
tk.Button(master, 
          text='ORDER Number', 
          command=write_slogan).grid(row=3, 
                                    column=1, 
                                    sticky=tk.W, 
                                    pady=4)

tk.mainloop()

我应该如何在弹出窗口而不是终端上打印以上代码输出?

2 个答案:

答案 0 :(得分:1)

在tkinter窗口而不是终端中打印消息

如果您只想在root窗口中打印消息,则可以在以下代码中使用类似这样的label小部件:

import tkinter as tk

master = tk.Tk()

def write_slogan():
    info_message = "Your message"
    tk.Label(master, text=info_message).grid(row=2, column=1) 

btn = tk.Button(master, text='ORDER Number', command=write_slogan)
btn.grid(row=3, column=1, sticky=tk.W, pady=4)

master.mainloop()

output

在单独的弹出窗口中打印邮件

您可以使用tkinter messagebox模块中的消息框来弹出一些信息,并在其中显示您的信息消息。

import tkinter as tk
import tkinter.messagebox as tkmb

def write_slogan():
    info_message = "Your message"
    # info message box
    tkmb.showinfo("Output", info_message)

master = tk.Tk()

btn = tk.Button(master, text='ORDER Number', command=write_slogan)
btn.grid(row=3, column=1, sticky=tk.W, pady=4)

master.mainloop()

output

将顶级窗口创建为弹出窗口

import tkinter as tk
import tkinter.messagebox as tkmb

def write_slogan():
    # toplevel window
    top_win = tk.Toplevel(master)
    top_win.title('Toplevel')
    info_message = "Your message"
    # info message box
    tk.Label(top_win, text=info_message).grid(row=0, column=0) 

master = tk.Tk()
master.title('Master')

btn = tk.Button(master, text='ORDER Number', command=write_slogan)
btn.grid(row=3, column=1, sticky=tk.W, pady=4)

master.mainloop()

output

答案 1 :(得分:0)

因此,如果您有要打印的消息(水果)列表,则可以使用以下方法保存以前的结果并打印新的消息。

Stream

输出:

gui window

  

点击import tkinter as tk window = tk.Tk() # list of fruits fruits = ['Mango', 'Apple', 'Orange', 'Banana', ] #action to be performed when button clicked def clicked(): for ind, fruit in enumerate(fruits): # print names in the tkinter window # create a label widget names_label = tk.Label(window) # give it a position using grid names_label.grid(row=int(ind)+1, column=0) # print the fruit name in the label names_label.config(text=fruit) btn = tk.Button(window, text="Print fruits", command=clicked) btn.grid(column=0, row=0, padx=30, pady=2) window.mainloop() 按钮以打印所有水果名称

gui window 2

这里要了解的重要一点是Print fruits循环用于创建与列表中元素数量相等的for小部件,列表项Label用于创建为这些标签小部件赋予indexrow位置。

在顶级窗口中打印名称

column

输出:

toplevel gui