首页 > 解决方案 > Tkinter 按钮获取变量未找到错误

问题描述

我正在尝试使用 tkinter 创建一个程序,该程序允许员工单击“打卡”按钮,该按钮获取当前时间并创建一个新按钮“打卡”,单击“打卡”按钮后,该按钮再次获取当前时间,然后显示每个按钮点击的时间增量的总小时数。我的问题是由于未定义“ClockedIn”变量,程序没有返回总工作时间。我相信这是代码安排的问题,但我被卡住了。有谁知道如何解决这一问题?我是初学者编码器,并感谢任何反馈。谢谢你。

我的代码如下:

from tkinter import *
import tkinter as tk
from tkinter import ttk
import time
import datetime
window = Tk()


def onclick1():
    label = tk.Label(text ="Clocked In")
    label.grid(row = 1, column = 3)
    label2 = tk.Label(text = time.strftime("%I:%M"))
    label2.grid(row =1, column = 5)
    CLockedIn = time.time()
    button2 = ttk.Button(window, text ="Clock Out")
    button2.grid(row = 2, column = 1)
    button2.config(command = onclick2)

def onclick2():
        label4 = tk.Label(text ="Clocked Out")
        label4.grid(row = 2, column = 3)
        ClockOut = time.time()
        label5 = tk.Label(text = time.strftime("%I:%M"))
        label5.grid(row =2, column = 5)
        Hours = int(ClockOut-CLockedIn)
        HoursLabel= tk.Label(Hours)
        HoursLabel.grid(row = 3, column = 4)

btn1 = ttk.Button(window, text = "Clock In")
btn1.grid(row=1,column=1)
btn1.config(command= onclick1)



window.mainloop()

标签: pythonloopsdatetimetkinter

解决方案


正如错误所说,您需要添加一个全局变量CLockedIn。对变量使用大写字母不是一个好习惯。当您添加时差时,它将显示secondsnot in 中的差异hours

from tkinter import *
import tkinter as tk
from tkinter import ttk
import time
import datetime
window = Tk()

clocked_in = 0
def onclick1():
    global clocked_in
    label = tk.Label(text ="Clocked In")
    label.grid(row = 1, column = 3)
    label2 = tk.Label(text = time.strftime("%I:%M"))
    label2.grid(row =1, column = 5)
    clocked_in = time.time()
    button2 = ttk.Button(window, text ="Clock Out")
    button2.grid(row = 2, column = 1)
    button2.config(command = onclick2)

def onclick2():
        label4 = tk.Label(text ="Clocked Out")
        label4.grid(row = 2, column = 3)
        clocked_out = time.time()
        label5 = tk.Label(text = time.strftime("%I:%M"))
        label5.grid(row =2, column = 5)
        hours = int(clocked_out-clocked_in)
        hoursLabel= tk.Label(text=hours)
        hoursLabel.grid(row = 3, column = 4)

btn1 = ttk.Button(window, text = "Clock In")
btn1.grid(row=1,column=1)
btn1.config(command= onclick1)

window.mainloop()

推荐阅读