繁体   English   中英

python tkinter 按钮命令不起作用

[英]python tkinter button command does not work

我正在尝试在 python tkinter 中创建一个程序,用户首先必须登录,然后关闭第一页并打开新页面,其中包含一些按钮。

按钮必须在单击时更改其颜色和文本,但它不执行任何操作

from tkinter import *


def button_clicked(button):
    Button(button).configure(bg="red", text="not Active")


def open_setting_page():
    loginPage.destroy()
    setting_page = Tk()
    setting_page.title("Setting")
    setting_page.geometry("400x300")

    b2 = Button(setting_page, text="Active", height=5, width=10, bg="green",command=lambda:button_clicked(b2)).grid(row=0, column=0)
    b3 = Button(setting_page, text="Active", height=5, width=10, bg="green",command=lambda:button_clicked(b3)).grid(row=0, column=1)
    setting_page.mainloop()






#program starts here

loginPage = Tk()
loginPage.title("Security System")
loginPage.geometry("400x300")
Label(text="\n\n\n\n").pack()
l1 = Label(text="Enter Password:")
l1.pack()

password_entry = Entry()
password_entry.insert(0, "Enter Your Password...")
password_entry.pack()
b1 = Button(text="Login", command=open_setting_page)
b1.pack()
loginPage.mainloop()

我希望在单击时更改按钮颜色和文本,但在单击它时会发生注释。

这段代码有两个问题:

  1. open_setting_page() -> 变量b2b3变为None因为Button(XXX).grid()返回None -> 让按钮创建和网格放置分为 2 个步骤。
  2. button_clicked(button) function -> Button(button).configure中是错误的。 它应该是button.configure(XX)来获取你给 function 的按钮。

下面是这两个函数的样子:

def button_clicked(button):
    button.configure(bg="red", text="not Active")


def open_setting_page():
    loginPage.destroy()
    setting_page = Tk()
    setting_page.title("Setting")
    setting_page.geometry("400x300")

    b2 = Button(setting_page, text="Active", height=5, width=10, bg="green", command=lambda: button_clicked(b2))
    b3 = Button(setting_page, text="Active", height=5, width=10, bg="green", command=lambda: button_clicked(b3))
    b2.grid(row=0, column=0)
    b3.grid(row=0, column=1)

    setting_page.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM