python - 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()
解决方案
正如错误所说,您需要添加一个全局变量CLockedIn
。对变量使用大写字母不是一个好习惯。当您添加时差时,它将显示seconds
not 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()
推荐阅读
- python - 如何使用用户定义的消息从 python pandas 导出数据
- c++ - C ++以正确的方式在堆上声明一个静态连续多维数组
- swift - 如何创建图像数组,并在 Swift 中使用 draw() 将它们绘制出来?
- http - HTTP KeepAlive 可以作为 TCP KeepAlive 的替代品吗?
- python - 使用numpy数组时如何处理itertools.product?
- c# - 为什么在使用 VS Installer 时出现“无法加载文件或程序集”?
- android - 无法在 Playstore 中按应用名称找到应用
- vb.net - VB.NET:如何将所需数据从 Datagrid 视图 ComboBoxColumn 自动填充到另一个 ComboBoxColumn
- powershell - 使用 wgrib2 将 grib2 转换为 netcdf:批量问题
- r - R中滞后的单列移位值