【问题标题】:How to make a button print out certain text? - Tkinter如何使按钮打印出某些文本? - Tkinter
【发布时间】:2016-05-10 01:41:44
【问题描述】:

下面,我创建了一个代码来跟踪一个人正在跑步的圈数。目前,我创建的按钮跟踪圈数和时间,但不在 GUI 窗口上。我想知道如何使代码中的数据显示在 GUI 窗口上。

from Tkinter import *
import time

laps=[0]
gui=Tk()
gui.geometry("200x100")
gui.title("lapping")

def afterbutton():
    label_1=Label(gui,text=end())

def end():
    end = time.time()
    elapsed = end - start
    laps[0]+=1
    print "%s seconds" % (elapsed)
    print "%s lap(s)" % (laps)

starting = raw_input("start? (s to start)")

if starting == "s":
    start = time.time()

button1=Button(gui,command=afterbutton,text="lap")
button1.grid()
button1.pack()

gui.mainloop()

【问题讨论】:

    标签: python user-interface tkinter


    【解决方案1】:

    您需要在创建按钮的同时创建标签。你需要把它放在网格中并打包,就像你对按钮所做的那样。然后,当单击按钮时,您所要做的就是更改标签的文本。这是它的样子:

    # python 3
    from Tkinter import *
    import time
    
    laps=[0]
    gui=Tk()
    gui.geometry("200x100")
    gui.title("lapping")
    
    def end():
        end = time.time()
        elapsed = end - start
        laps[0] += 1
        s = "%s seconds %s laps" % (elapsed,laps)
        label1['text'] = s
        print("%s seconds" % (elapsed))
        print("%s lap(s)" % (laps))
    
    starting = raw_input("start? (s to start)")
    
    if starting == "s":
        start = time.time()
    
    button1 = Button(gui, command=end, text="lap")
    button1.grid()
    button1.pack()
    label1 = Label(gui)
    label1.grid()
    label1.pack()
    
    gui.mainloop()
    

    函数afterbutton消失了;所有工作都由end() 完成。我保留了你的大部分程序,但我使用的是 py3,所以 print 是一个函数而不是一个语句。你必须为 py2 解决这个问题。标签的文本设置:

    label1['text'] = s
    

    当你第一次看到它时,这是一种有点奇怪的语法。

    顺便说一句,我不明白你为什么使用单元素列表来表示圈数而不是简单的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多