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()
我应该如何在弹出窗口而不是终端上打印以上代码输出?
答案 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()
在单独的弹出窗口中打印邮件
您可以使用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()
将顶级窗口创建为弹出窗口
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()
答案 1 :(得分:0)
因此,如果您有要打印的消息(水果)列表,则可以使用以下方法保存以前的结果并打印新的消息。
Stream
输出:
点击
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()
按钮以打印所有水果名称
这里要了解的重要一点是Print fruits
循环用于创建与列表中元素数量相等的for
小部件,列表项Label
用于创建为这些标签小部件赋予index
和row
位置。
在顶级窗口中打印名称
column
输出: