簡體   English   中英

如何使用 Tkinter 簡單地更新標簽

[英]How to simply Update Labels with Tkinter

我是一名正在研究編程問題的學生。 我想知道我是否可以幫助使用 Tkinter 和標簽項目。

我目前正在為我的程序使用標簽,因為它們看起來最好,並且與文本或其他類似的東西相比更容易格式化。 反正...

我目前遇到的問題是我的標簽不會更新,我目前正在使用以下代碼:

from tkinter import *
import sys

#Window Initilisation
root = Tk()
root.title('CafeAuLait Ordering')

#Product Prices
Cappu_CSt = (3.75) #Cappucino cost

#Defining Variables
TotaldCost = (0)
Reciptext = ('Developer Version')

Display = Label(root, width=35, bg='white', height=10, text=str(Reciptext))
Display.grid(row=1,column=3, columnspan=4, rowspan=8)
 
def button_cappucino():
    global TotaldCost
    global Reciptext
    global Cappu_CSt
    TotaldCost = TotaldCost + Cappu_CSt
    Display = ((str(Reciptext) + '''
    Cappucino ----- $'''+ str(Cappu_CSt)))
    print('Test')

cappucino = Button(root, text='1x Cappucino',width=10 ,borderwidth=5, command=button_cappucino)
price_LabelCCP = Label(root, text='---$3.75', bg='#FFF6AD')

cappucino.grid(row=1, column=1)
price_LabelCCP.grid(row=1, column=2)

root.mainloop()

我在終端中返回測試,這表明按鈕確實在運行,但盡管如此,標簽不會更新,只保留文本“開發人員版本” 有誰知道我可以更新標簽的簡單方法? 非常感謝。

您正在嘗試將文本直接分配給小部件。 您必須將文本分配給適當的小部件屬性。 不過,您還有其他問題。 我修正了你的邏輯並在評論中解釋了它。

#don't pollute your namespace with *
import tkinter as tk

#Window Initilisation
root = tk.Tk()
root.title('Cafe-Au-Lait Ordering')

#your variables had strange names and value syntax
pricelist = []
purchases = []
header    = 'Developer Version\n'
offset    = 0    #first line items will be printed on ~ set internally
selected  = -1   #used as a purchase index ~ -1 means nothing is selected


#by listing the properties of your items this way
#~you can create and manage buttons dynamically
items =[
    {'name':'Cappucino',    'cost':3.89},
    {'name':'Mochasippi',   'cost':3.59},
    {'name':'Black Coffee', 'cost':2.19},
    {'name':'Water',        'cost':1.59},
    {'name':'Orange Juice', 'cost':1.89},
    {'name':'Milk',         'cost':1.89},
    {'name':'Croissant',    'cost':2.59},
    {'name':'Danish',       'cost':2.59},
]


#force an extra dummy row to take up all remaining space
root.grid_rowconfigure(len(items), weight=1)
#force Text display to resize with window
root.grid_columnconfigure(2, weight=1)

#only Text widgets are truly multiline
receipt_txt = tk.Text(root, width=35, bg='white', cursor='arrow', height=20)
receipt_txt.grid(row=0, column=2, rowspan=len(items)+1, sticky='nswe') #span to include dummy row

#init receipt
receipt_txt.insert('1.0', header) 
receipt_txt.insert('4.0', '\ntotal: $0.00') 
receipt_txt.tag_configure('selected', background='#FFF6AD')
receipt_txt.config(state='disabled')       #disable receipt


#select a line for complete item deletion
def select(event):
    global selected
    global offset
    
    #line number that was clicked
    b = int(receipt_txt.index('@%d,%d' % (event.x, event.y)).split('.')[0])
    #the "total: $00.00" line number
    e = int(receipt_txt.index('end-1c').split('.')[0])
    #the text
    t = receipt_txt.get(f'{b}.0', f'{b}.end').strip()
    #if the line falls within the item range and has text
    if b in range(offset, e) and t:
        #reposition selected tag
        receipt_txt.tag_remove("selected", '1.0', 'end')
        receipt_txt.tag_add("selected", f'{b}.0', f'{b}.end')
    
    #used as 'purchases' index    
    selected = b - offset


#rewrite receipt and reconsider pricelist, selected and offset
def retotal():
    global pricelist
    global purchases
    global selected
    global offset
    global header
    
    selected  = -1                          #unset selected
    pricelist = []                          #reset pricelist
    
    receipt_txt.config(state='normal')      #enable receipt for writing
    receipt_txt.delete('1.0', 'end')        #remove all text
    receipt_txt.insert('1.0', header)       #rewrite header
    
    #store the line that items will start on
    offset   = int(receipt_txt.index('end-1c').split('.')[0]) + 1 #because item starts with \n
    
    #rewrite all items
    for it in purchases:
        if it:
            pricelist.append(it["cost"])                 #rewrite pricelist
            strcost = f'${format(it["cost"], ".2f")}'    #create string of cost
            #write item to receipt
            receipt_txt.insert('end-1c', f'\n{it["name"]:<16} ---- {strcost:>{16-len(strcost)}}')
                                          
    #rewrite "total" line
    receipt_txt.insert('end-1c', f'\n\ntotal: ${format(sum(pricelist), ".2f")}') 
    receipt_txt.config(state='disabled')    #disable receipt


#handles all item purchases
def add_item(item):
    global purchases
    
    purchases.append(item) #append to purchases
    retotal()              #reconsider receipt


#handles all item removals    
def remove_item(event=None, purchase_num=None):
    global purchases
    global selected
    
    selected = selected if not purchase_num else purchase_num
    
    if selected in range(0, len(purchases)):
        purchases.pop(selected) #append to purchases
        retotal()              #reconsider receipt


#unset selected    
def unselect(event=None):
    global selected
    selected = -1    


#receipt is left-clicked
receipt_txt.bind('<1>', select)
#receipt loses focus ~ unset 'selected'
receipt_txt.bind('<FocusOut>', unselect)
#delete key was pressed ~ remove purchase and retotal
receipt_txt.bind('<Delete>', remove_item)

#create all register buttons dynamically
for i, v in enumerate(items):
    tk.Button(root, text=v['name'], width=15, command=lambda v=v: add_item(v)).grid(row=i, column=0, sticky='nw', pady=0)
    tk.Label(root, text=f"${format(v['cost'], '.2f')}", bg='#FFF6AD').grid(row=i, column=1)


root.mainloop()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM