[英]Update label text after pressing a button in Tkinter
我想知道如何在單擊按鈕后更改標簽文本。 例如:
from Tkinter import *
import tkMessageBox
def onclick():
pass
root = Tk()
root.title("Pantai Hospital")
L1 = Label(root, text='Welcome to Pantai Hospital!')
L1.pack()
L2 = Label(root, text='Login')
L2.pack()
L3 = Label(root, text = "Username:")
L3.pack( side = LEFT, padx = 5, pady = 10)
username = StringVar()
E1 = Entry(root, textvariable = username, width = 40)
E1.pack ( side = LEFT)
L4 = Label(root, text = "Password:")
L4.pack( side = LEFT, padx = 5, pady = 10)
password = StringVar()
E2 = Entry(root, textvariable = password, show = "*", width = 40)
E2.pack( side = LEFT)'`
單擊按鈕后,我想將這些標簽username
和password
以及輸入字段更改為另一個不同的標簽。 我怎么做?
“如何在按下按鈕時執行任何操作”的答案應該在任何教程中。
例如在effbot書中: Button
使用command=
將函數名稱分配給按鈕。
(順便說一句:函數名稱(或回調)表示不帶括號和參數的名稱)
btn = Button(root, text="OK", command=onclick)
“如何更改標簽文本”的答案也應該在任何教程中。
lbl = Label(root, text="Old text")
# change text
lbl.config(text="New text")
# or
lbl["text"] = "New text"
如果您想將Entry
更改為Label
然后刪除/隱藏Entry
( widget.pack_forget()
) 或銷毀它 ( widget.destroy()
) 並創建Label
。
順便說一句:您可以禁用Entry
而不是制作Label
( ent.config(state='disabled')
)
編輯:我刪除了lbl.["text"]
中的點
在編寫 button.pack() 之后編寫 lbl.pack() 一小段代碼,用於在單擊按鈕時顯示值的變化。 這樣做是為了在您執行按鈕單擊后顯示在標簽中所做的更改。
from tkinter import *
root = Tk(className = "button_click_label")
root.geometry("200x200")
message = StringVar()
message.set('hi')
l1 = Label(root, text="hi")
def press():
l1.config(text="hello")
b1 = Button(root, text = "clickhere", command = press).pack()
l1.pack()
root.mainloop()
我只是一個入門級的 python 程序員。 原諒,如果我錯了請糾正我! 干杯!
動態更改標簽的另一種方法。 在這里,我們使用 lambda 來顯示對標簽顯示的多項調整。 如果您想更改一個標簽,只需忽略 lambda 並調用不帶參數的函數(在本例中為 1 和 2)。 請記住確保在為此用途創建標簽時使用 separate.pack 方法,否則當該函數嘗試使用 .pack 方法配置一行時,您會收到錯誤消息。
from tkinter import *
root = Tk(className = "button_click_label")
root.geometry("200x200")
def press(x):
if x == 1:
l1.config(text='hello')
else:
l1.config(text='hi')
b1 = Button(root, text = "click me", command = lambda:press(1)).pack()
b2 = Button(root, text = 'click me', command = lambda:press(2)).pack()
l1 = Label(root, text="waiting for click")
l1.pack()
root.mainloop()
這是一個示例,其中我創建了一個帶有標簽的基本圖形用戶界面。 然后我更改了標簽文本。
import tkinter as tk
from tkinter import *
app = tk.Tk()
#creating a Label
label = Label(app, text="unchanged")
label.pack()
#updating text
label.config(text="changed")
app.mainloop()
這應該有效:
from tkinter import *
root = Tk(className = "button_click_label")
root.geometry("200x200")
message = StringVar()
message.set('hi')
l1 = Label(root, text="hi")
l1.pack()
def press():
l1.config(text="hello")
b1 = Button(root, text = "clickhere", command = press).pack()
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.