简体   繁体   English

如何在tkinter中显示函数的值

[英]How to display the value of function in tkinter

I am new to python and tkinter and I have decided that I will make a stopwatch. 我是python和tkinter的新手,所以我决定制作秒表。 I have gooled alot and find many useful information, but I still haven't found how to display value of a function in tkinter. 我已经找到很多有用的信息,但是我仍然没有找到如何在tkinter中显示函数的值。 Here is my current code: 这是我当前的代码:

import time
from tkinter import*
import os

root = Tk()

def clock(event):
    second = 0
    minute = 0
    hour = 0  
    while True:
        time.sleep(0.99)
        second +=1
        print(hour,":",minute,":",second)
    return

def stop(event):
    time.sleep(1500)

def clear(event):
    os.system('cls')


button1 = Button(root, text="Start")
button2 = Button(root, text="Stop")
button3 = Button(root, text="Clear")

button1.bind("<Button-1>", clock)
button2.bind("<Button-1>", stop)
button3.bind("<Button-1>", clear)

button1.grid(row=2, column=0, columnspan=2)
button2.grid(row=2, column=2, columnspan=2)
button3.grid(row=2, column=4, columnspan=2)


root.mainloop()

I am aware that the code isn't perefect yet(especially the functions stop and clear). 我知道代码还没有完善(特别是功能停止并清除)。

You might consider using callback functions (call your function when something happens? when clicking a button for example) 您可能会考虑使用回调函数(例如,发生某种事情时调用您的函数?例如单击按钮时)

In Tkinter, a callback is Python code that is called by Tk when something happens. 在Tkinter中,回调是Python代码,当某些事情发生时,Tk会调用它。 For example, the Button widget provides a command callback which is called when the user clicks the button. 例如,“按钮”小部件提供了一个命令回调,当用户单击按钮时会调用该回调。 You also use callbacks with event bindings. 您还可以将回调与事件绑定一起使用。

You can use any callable Python object as a callback. 您可以使用任何可调用的Python对象作为回调。 This includes ordinary functions, bound methods, lambda expressions, and callable objects. 这包括普通函数,绑定方法,lambda表达式和可调用对象。 This document discusses each of these alternatives briefly. 本文档简要讨论了每种替代方法。 Example: To use a function object as a callback, pass it directly to Tkinter. 示例:要将函数对象用作回调,请将其直接传递给Tkinter。

from Tkinter import * 从Tkinter进口*

def callback():
    print "clicked!"

b = Button(text="click me", command=callback)
b.pack()

mainloop()

http://effbot.org/zone/tkinter-callbacks.htm http://effbot.org/zone/tkinter-callbacks.htm

It's unclear from your sample code which function's value you want to display. 从示例代码尚不清楚要显示哪个函数的值。

Regardless, a good way to do accomplish something like that in tkinter is by creating instances of its StringVar control class and then specifying them as the textvariable option of another widget. 无论如何,这样做达到这个目的的一个好办法tkinter是通过创建实例STRINGVAR控制类 ,然后指定它们作为textvariable另一个工具选项。 After this is done, any changes to the value of the StringVar instance will automatically update the associated widget's text. 完成此操作后,对StringVar实例的值进行的任何更改都将自动更新关联的小部件的文本。

The code below illustrates this: 下面的代码说明了这一点:

import os
import time
import tkinter as tk

class TimerApp(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master=None)
        self.grid()
        self.create_widgets()
        self.elapsed = 0
        self.refresh_timer()
        self.after_id = None  # used to determine and control if timer is running

    def create_widgets(self):
        self.timer = tk.StringVar()
        self.timer.set('')
        self.timer_label = tk.Label(self, textvariable=self.timer)
        self.timer_label.grid(row=1, column=2)

        self.button1 = tk.Button(self, text="Start", command=self.start_clock)
        self.button1.grid(row=2, column=0, columnspan=2)
        self.button2 = tk.Button(self, text="Stop", command=self.stop_clock)
        self.button2.grid(row=2, column=2, columnspan=2)
        self.button3 = tk.Button(self, text="Clear", command=self.clear_clock)
        self.button3.grid(row=2, column=4, columnspan=2)

    def start_clock(self):
        self.start_time = time.time()
        self.after_id = self.after(1000, self.update_clock)

    def stop_clock(self):
        if self.after_id:
            self.after_cancel(self.after_id)
            self.after_id = None

    def clear_clock(self):
        was_running = True if self.after_id else False
        self.stop_clock()
        self.elapsed = 0
        self.refresh_timer()
        if was_running:
            self.start_clock()

    def update_clock(self):
        if self.after_id:
            now = time.time()
            delta_time = round(now - self.start_time)
            self.start_time = now
            self.elapsed += delta_time
            self.refresh_timer()
            self.after_id = self.after(1000, self.update_clock)  # keep updating

    def refresh_timer(self):
        hours, remainder = divmod(self.elapsed, 3600)
        minutes, seconds = divmod(remainder, 60)
        self.timer.set('{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds))

app = TimerApp()
app.master.title('Timer')
app.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM