简体   繁体   English

python tkinter 按钮命令不起作用

[英]python tkinter button command does not work

I'm trying to create a program in python tkinter which user first have to login, then the first page is closed and new one opens with some buttons inside.我正在尝试在 python tkinter 中创建一个程序,用户首先必须登录,然后关闭第一页并打开新页面,其中包含一些按钮。

button must change it's color and text on click but it does not do anything按钮必须在单击时更改其颜色和文本,但它不执行任何操作

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

I want the buttons color and text be changed on click but noting happens when I click it.我希望在单击时更改按钮颜色和文本,但在单击它时会发生注释。

there are two problems in this code:这段代码有两个问题:

  1. in open_setting_page() -> the variables b2 and b3 become None because Button(XXX).grid() returns None -> lets separate the button creation and the grid placement into 2 steps.open_setting_page() -> 变量b2b3变为None因为Button(XXX).grid()返回None -> 让按钮创建和网格放置分为 2 个步骤。
  2. in button_clicked(button) function -> Button(button).configure is wrong.button_clicked(button) function -> Button(button).configure中是错误的。 it should be button.configure(XX) to get hold of the button that you gave to the function.它应该是button.configure(XX)来获取你给 function 的按钮。

Here is how these two functions could look like:下面是这两个函数的样子:

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