如何更新tkinter中的"live"文本框?

Pyt*_*ner 2 python tkinter

我想问一下如何在python中创建一个"LIVE"文本框?该程序是自动售货机的模拟器(下面的代码).我希望有一个显示实时信用更新的文本框你如何在tkinter中做到这一点?

例如:假设在窗口中间有一个信用卡,其中包含0.当10p按下按钮,对信贷的框应该从"0"更改为"0.10".有没有可能在tkinter和python 3.3.2中做?先感谢您!

import sys
import tkinter as tk

credit = 0
choice = 0

credit1 = 0
coins = 0
prices = [200,150,160,50,90]
item = 0
i = 0
temp=0
n=0
choice1 = 0
choice2 = 0

credit1 = 0
coins = 0
prices = [200,150,160,50,90]
item = 0
i = 0
temp=0
n=0
choice1 = 0
choice2 = 0

def addTENp():
    global credit
    credit+=0.10

def addTWENTYp():
    global credit
    credit+=0.20

def addFIFTYp():
    global credit
    credit+=0.50

def addPOUND():
    global credit
    credit+=1.00

def insert():
    insert = Tk()

    insert.geometry("480x360")
    iLabel = Label(insert, text="Enter coins.[Press Buttons]").grid(row=1, column=1)

    tenbutton = Button(insert, text="10p", command = addTENp).grid(row=2, column=1)
    twentybutton = Button(insert, text="20p", command = addTWENTYp).grid(row=3, column=1)
    fiftybutton = Button(insert, text="50p", command = addFIFTYp).grid(row=4, column=1)
    poundbutton = Button(insert, text="£1", command = addPOUND).grid(row=5, column=1)


insert()
Run Code Online (Sandbox Code Playgroud)

tob*_*s_k 8

你当然可以!只需在框架中添加另一个标签,并在text调用其中一个添加函数时更新该属性.此外,您可以使用一个add函数来简化该代码,以获取所有不同的金额.

def main():
    frame = Tk()
    frame.geometry("480x360")

    Label(frame, text="Enter coins.[Press Buttons]").grid(row=1, column=1)
    display = Label(frame, text="") # we need this Label as a variable!
    display.grid(row=2, column=1)

    def add(amount):
        global credit
        credit += amount
        display.configure(text="%.2f" % credit)

    Button(frame, text="10p", command=lambda: add(.1)).grid(row=3, column=1)
    Button(frame, text="20p", command=lambda: add(.2)).grid(row=4, column=1)
    Button(frame, text="50p", command=lambda: add(.5)).grid(row=5, column=1)
    Button(frame, text="P1",  command=lambda: add(1.)).grid(row=6, column=1)
    frame.mainloop()

main()
Run Code Online (Sandbox Code Playgroud)

还有一点:

  • 请注意,您定义了许多变量两次
  • 你不应该给一个与函数同名的变量,因为这会影响函数
  • 可能只是一个复制粘贴错误,但你忘了调用mainloop,你的tkinter导入与你使用类的方式不一致(没有tk前缀)
  • 您可以在创建GUI元素后立即进行布局,但请注意,在这种情况下,GUI元素不会绑定到变量,而是布局函数的结果,即 None