按下Tkinter中的按钮后更新标签文本

时间:2016-01-09 05:05:06

标签: python user-interface 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)'`

我想在点击按钮后将这些标签usernamepassword以及输入字段更改为另一个不同的标签。我怎么做?

5 个答案:

答案 0 :(得分:4)

在任何教程中都应该回答“如何按下按钮” 例如,在 effbot book: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,请删除/隐藏Entrywidget.pack_forget())或销毁它(widget.destroy())并创建{{1} }}

btw:你可以停用Label而不是EntryLabel

编辑:我删除了ent.config(state='disabled')

中的点

答案 1 :(得分:1)

编写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程序员。 原谅,如果我错了,请纠正我! 干杯!

答案 2 :(得分:1)

这是我用标签创建基本gui的示例。然后我改变了标签文字。

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

答案 3 :(得分:1)

另一种动态更改标签的方法。在这里,我们使用 lambda 来显示对标签显示的多个调整。如果您想更改一个标签,只需忽略 lambda 并调用不带参数的函数(在本例中为 1 和 2)。请记住,在为此用途创建标签时确保将 .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()

答案 4 :(得分:0)

这应该有效:

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()
相关问题