【问题标题】:How to change date when button is clicked?单击按钮时如何更改日期?
【发布时间】:2020-01-28 02:04:01
【问题描述】:

我有一个带有datechoose date 按钮的tkinker 窗口,我将其称为主页。当用户选择日期时,我希望在主页中更新日期。我在datecheck 函数中重新调整了选定的日期。然后我想用返回日期更新主页日期。我不知道如何使它成为可能。帮我解决一下。

这是我编写的示例代码:

from tkinter import *
from tkinter import ttk
from tkinter import scrolledtext
import time
import tkinter.messagebox
from datetime import datetime
import tkinter as tk
import sys
import os
from tkcalendar import Calendar, DateEntry
from datetime import date
import multiprocessing


def datecheck():
    global date_string
    root = Tk()
    s = ttk.Style(root)
    s.theme_use('clam')
    def print_sel():
        global date_string,timestamp
        date_string =cal.selection_get()
        date_string=date_string.strftime("%d-%b-%Y")
        print("returned_date",date_string)
        root.destroy()
    today = date.today()
    d = int(today.strftime("%d"))
    m= int(today.strftime("%m"))
    y =int(today.strftime("%Y"))
    cal = Calendar(root,
                   font="Arial 14", selectmode='day',
                   cursor="hand1",   day=d,month=m,year=y)
    cal.pack(fill="both", expand=True)
    ttk.Button(root, text="ok", command=print_sel).pack()
def homepage():
    global date_string,timestamp
    if date_string == "":
            timestamp = datetime.now().strftime("%d-%b-%Y")

    else:
        timestamp = date_string
    def close_window():
        window.destroy()

    window = Tk()
    window.title("Status Uploader")
    window.geometry('500x200')
    Label(window,
          text="Status Uploader",
          fg="blue",
          bg="yellow",
          font="Verdana 10 bold").pack()
    Label(window,
          text="Date : {}".format(timestamp),
          fg="red",
          bg="yellow",
          font="Verdana 10 bold").pack()

    txt = scrolledtext.ScrolledText(window, width=60, height=9.5)
    txt.pack()
    button = Button(window, fg='white', bg='blue',
                    text="Choose Date", command=datecheck)
    button.place(x=35, y=152)
    button = Button(window, fg='white', bg='red',
                    text="Close", command=close_window)
    button.place(x=405, y=152)
    window.mainloop()        

global date_string,timestamp
date_string = ""
homepage()

截图:

【问题讨论】:

  • 你做了什么来调试这个?您是否已确认其他进程已启动?您是否确认您实际上正在更改datestring?您是否知道仅更改 timestamp 不会改变显示屏上的任何内容?
  • 是的,在tkintermainloop() 运行时(必须调用它以便 GUI 可以处理用户事件)执行其他操作的常用方法是使用通用小部件after() 方法来安排对函数的定期调用。
  • @Bryan Oakley,是的,这两个过程开始了。
  • @crussalty:删除所有与multiprocessing相关的东西并遵循此模式python calendar widget - return the user-selected date
  • @Bryan Oakley,我已经删除了多处理并返回了日期。我已经更新了代码。之后,如何用我的returned_date更新homepage date

标签: python python-3.x tkinter python-multiprocessing tkcalendar


【解决方案1】:

这是您的代码的一个版本,它不使用 multiprocessing,因为我认为没有必要使用它 - 尽管我真的不明白您要对这两个 date_string 做什么和timestamp 全局变量以及它们之间的关系。下面代码中发生的所有事情都是后者被fun() 函数定期复制到第一个,该函数每 1000 毫秒调用一次(例如每秒一次)。

这是通过使用通用的tkinter 小部件after{} 方法来定期检查日期和时间并更新全局变量来完成的——在这种情况下,multiprocessing 不需要这样做。

为了让标签显示用户选择新日期后要更改的日期,我向datecheck() 函数添加了一个date_label 参数并修改了homepage() 函数以将其作为参数传递给通过单击 Choose Date Button 调用它时的函数。

我通常还清理了代码并使其遵循PEP 8 - Style Guide for Python Code 准则,以使其更易于阅读和维护。

from datetime import date, datetime
from functools import partial
import os
import sys
from tkcalendar import Calendar, DateEntry
from tkinter import ttk
from tkinter import scrolledtext
import tkinter as tk

def datecheck(date_label):
    global date_string, timestamp

    root = tk.Toplevel()
    s = ttk.Style(root)
    s.theme_use('clam')

    def print_sel():
        global date_string

        cal_selection = cal.selection_get()
        date_string = cal_selection.strftime("%d-%b-%Y")
        # Update the text on the date label.
        date_label.configure(text="Date : {}".format(date_string))
        root.destroy()

    today = date.today()
    d = int(today.strftime("%d"))
    m = int(today.strftime("%m"))
    y =int(today.strftime("%Y"))

    cal = Calendar(root,
                   font="Arial 14", selectmode='day',
                   cursor="hand1", day=d,month=m, year=y)
    cal.pack(fill="both", expand=True)

    ttk.Button(root, text="ok", command=print_sel).pack()


def homepage():
    global date_string, timestamp

    if date_string == "":
        timestamp = datetime.now().strftime("%d-%b-%Y")
    else:
        timestamp = date_string

    def close_window():
        window.destroy()

    window = tk.Tk()
    window.title("Status Uploader")
    window.geometry('500x200')
    tk.Label(window,
             text="Status Uploader",
             fg="blue",
             bg="yellow",
             font="Verdana 10 bold").pack()
    date_label = tk.Label(window,
                          text="Date : {}".format(timestamp),
                          fg="red",
                          bg="yellow",
                          font="Verdana 10 bold")
    date_label.pack()

    # Create callback function for "Choose Date" Button with data_label
    # positional argument automatically supplied to datecheck() function.
    datecheck_callback = partial(datecheck, date_label)

    txt = scrolledtext.ScrolledText(window, width=60, height=9.5)
    txt.pack()

    button = tk.Button(window, fg='white', bg='blue',
                       text="Choose Date",
                       command=datecheck_callback)
    button.place(x=35, y=152)
    button = tk.Button(window, fg='white', bg='red', text="Close", command=close_window)
    button.place(x=405, y=152)

    window.after(1000, fun, window)  # Start periodic global variable updates.
    window.mainloop()


def fun(window):
    """ Updates some global time and date variables. """
    global date_string, timestamp

    if date_string == "":
        timestamp = datetime.now().strftime("%d-%b-%Y")
    else:
        timestamp = date_string

    window.after(1000, fun, window)  # Check again in 1000 milliseconds.


# Define globals.
date_string = ""
timestamp = None

homepage() # Run GUI application.

【讨论】:

  • 咸味的外壳:很高兴听到它有帮助。编程tkinter 可能相当困难,因为它的文档记录很差,在许多方面都不是“pythonic”,而且它有很多“规则”,需要学习一定数量的“技巧”才能充分利用它——所以它可能不是学习 Python 语言基础知识的最快方法。无论如何,现在拥有一些像这样工作的东西确实可以在掌握它方面有很长的路要走。祝你工作顺利。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 2021-03-19
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多