在我给你工作代码之前,我想告诉你:
1)在传统知识(和Python)
ttk.Button(root, text='Last Date', command=example1)
您将名称与函数 (command=example1) 连接,但如果您更改
ttk.Button(root, text='Last Date', command=example1())
你会得到两个窗口,因为你运行自动功能
2)我不确定这是好的做法,但在这种情况下,您需要创建两个几乎相同的功能,但有一个不同的功能
print('next_date="{}"'.format(cal.selection_get()))
这是完整的工作代码:
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar
def example1():
def print_sel():
print('last_date="{}"'.format(cal.selection_get()))
def quit1():
top.destroy()
top = tk.Toplevel(root)
cal = Calendar(top,
font="Arial 14", selectmode='day',
cursor="hand1", year=2018, month=2, day=5)
cal.pack(fill="both", expand=True)
ttk.Button(top, text="ok", command=print_sel).pack()
ttk.Button(top, text="exit", command=quit1).pack()
def example2():
def print_sel():
print('next_date="{}"'.format(cal.selection_get()))
def quit1():
top.destroy()
top = tk.Toplevel(root)
cal = Calendar(top,
font="Arial 14", selectmode='day',
cursor="hand1", year=2018, month=2, day=5)
cal.pack(fill="both", expand=True)
ttk.Button(top, text="ok", command=print_sel).pack()
ttk.Button(top, text="exit", command=quit1).pack()
root = tk.Tk()
s = ttk.Style(root)
s.theme_use('clam')
ttk.Button(root, text='Last Date', command=example1).pack(padx=10, pady=10)
ttk.Button(root, text='Next Date', command=example2).pack(padx=10, pady=10)
root.mainloop()
如果使用类并获取值:
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar
class t:
def __init__(self):
self.root = tk.Tk()
self.s = ttk.Style(self.root)
self.s.theme_use('clam')
self.last_date = 'Last Date'
self.next_date = 'Next Date'
self.b1 = ttk.Button(self.root, text='Last Date', command=self.example1).pack(padx=10, pady=10)
self.b2 = ttk.Button(self.root, text='Next Date', command=self.example2).pack(padx=10, pady=10)
self.b3 = ttk.Button(self.root, text='show', command=self.my_print).pack(padx=10, pady=10)
self.root.mainloop()
def my_print(self):
print ('{}\n{}'.format(self.last_date, self.next_date))
def example1(self):
def print_sel():
print('"{}"'.format(cal.selection_get()))
self.last_date += str(cal.selection_get())
def quit1():
top.destroy()
top = tk.Toplevel(self.root)
cal = Calendar(top,
font="Arial 14", selectmode='day',
cursor="hand1", year=2018, month=2, day=5)
cal.pack(fill="both", expand=True)
ttk.Button(top, text="ok", command=print_sel).pack()
ttk.Button(top, text="exit", command=quit1).pack()
def example2(self):
def print_sel():
print('"{}"'.format(cal.selection_get()))
self.next_date += str(cal.selection_get())
def quit1():
top.destroy()
top = tk.Toplevel(self.root)
cal = Calendar(top,
font="Arial 14", selectmode='day',
cursor="hand1", year=2018, month=2, day=5)
cal.pack(fill="both", expand=True)
ttk.Button(top, text="ok", command=print_sel).pack()
ttk.Button(top, text="exit", command=quit1).pack()
tt = t()