from tkinter import *
import tkinter as tk
创建计数器
def a():
def counter_label(label):
counter=0
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000,count)
count()
label=tk.Label(frame,fg="red")
label.grid(row=0,column=1)
def create_widgets_in_frame():
Label(frame,text="TIME:",padx=25,pady=50,font=("arial",20,"bold"),bg="red",width=10).grid(row=0,column=0,sticky=W)
Button(frame,text="START",padx=25,pady=50,font=("arial",20,"bold"),command=a,bg="red",width=10).grid(row=1,column=0,sticky=E)
Button(frame,text="STOP",padx=25,pady=50,font=("arial",20,"bold"),bg="red",width=10).grid(row=1,column=1,sticky=E)
Button(frame,text="EXIT",padx=25,pady=50,font=("arial",20,"bold"),command = quit_program,bg="red",width=10).grid(row=1,column=2,sticky=E)
def call_frame_on_top():
frame.grid(column=0, row=0, padx=20, pady=5, sticky=W)
def quit_program():
root_window.destroy()
root_window=Tk()
root_window.geometry("1500x1000+0+0")
window_width = 1500
window_heigth = 1000
frame=Frame(root_window,bg="blue", width=window_width, height=window_heigth)
frame.grid(column=0, row=0, padx=20, pady=5, sticky=W)
create_widgets_in_frame()
root_window.configure(background="blue")
root_window.mainloop()
答案 0 :(得分:1)
在函数a()
中,您实际上从未调用counter_label
,因此它不会启动计数。您需要在函数外部定义counter
变量,以便使用global
关键字。
以下是您修改的代码:
from tkinter import *
import tkinter as tk
counter = 0 #Defining counter so you can use it with global
def a():
def counter_label(label):
counter=0
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000,count)
count()
label=tk.Label(frame,fg="red")
label.grid(row=0,column=1)
counter_label(label) #Calling the counter_label function
...