为什么启动按钮不执行计数器功能

时间:2016-05-31 12:09:39

标签: python-3.x tkinter

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

在根窗口内创建框架以保存其他GUI元素。必须在主程序中创建所有帧,否则无法在函数中访问它们。

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()

1 个答案:

答案 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

...