如何使用Tkinter简单地更新标签

2024-10-02 22:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名正在研究编程问题的学生。我想知道我是否可以帮你做一个标签和标签

我目前正在为我的程序使用标签,因为它们看起来最好,而且与文本或其他类似的东西相比,更容易格式化。无论如何

我目前的问题是我的标签不会更新,我目前正在使用以下代码:

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

我在终端中得到了测试,这表明按钮确实在运行,但尽管如此,标签并没有更新,只保留文本“开发者版本”,有人知道我更新标签的简单方法吗?非常感谢


Tags: textdisplaycolumnroot标签globalgridrow
1条回答
网友
1楼 · 发布于 2024-10-02 22:31:46

您正试图将文本直接分配给小部件。您必须将文本分配给适当的小部件属性。不过,你还有其他问题。我修正了你的逻辑,并在评论中解释了它

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

enter image description here

相关问题 更多 >