【问题标题】:Python tkinter create multiple variablesPython tkinter 创建多个变量
【发布时间】:2022-01-01 18:11:03
【问题描述】:

我开始使用 tkinter 和类方法进行编码。我尝试编写一个待办事项列表,我可以通过按下条目下方的按钮来创建多个条目。如果按下,条目旁边的按钮应更改条目的颜色。现在的问题是,当我创建多个条目时,按钮只会更改最新条目。所以我的问题是如何在创建时指定条目?

对于明显的错误抱歉,我是编码新手:p

import tkinter as tk
from tkinter.constants import ANCHOR, CENTER, X
from tkinter import messagebox

class App():

    def __init__(self):
        self.window = tk.Tk()
        self.window.title("To-Do-List")
        self.window.geometry("700x700")

        self.x_but, self.y_but = 0.05, 0.2 
        self.x_ent, self.y_ent = 0.05, 0.2
        self.x_but2 = 0.3
        self.check_var = True

        self.start_frame()
        self.grid1()
        self.window.mainloop()
        
    def start_frame(self):
        self.label1 = tk.Label(text="To Do List", font=("", 30))
        self.label1.place(relx=0.5, rely=0.05, anchor=CENTER)

    def grid1(self):
        self.button1 = tk.Button(text="Create", command= self.create_field)
        self.button1.place(relx = self.x_but, rely= self.y_but)

    def create_field(self):
        self.y_but += 0.05
        self.button1.place(relx= self.x_but, rely= self.y_but)

        self.entry1 = tk.Entry()
        self.entry1.place(relx= self.x_ent, rely= self.y_ent)
        

        self.button_check = tk.Button(text="✅", height= 1,command=self.check)
        self.button_check.place(relx= self.x_but2, rely=self.y_ent)
       



        self.y_ent += 0.05
    
    def check(self):
        if self.check_var:
            self.entry1.configure(bg="Green")
            self.check_var = False

        else:
            self.entry1.configure(bg="White")
            self.check_var = True

    



app = App()

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    您正在更改 self.entry1bg 每次创建条目时都会覆盖自身,因此当单击按钮时,它始终是最后一个条目。最简单的解决方案是为check 定义一个参数,然后将所需的条目作为参数传递给它。

    所以方法是:

    def check(self,ent):
        if self.check_var:
            ent.configure(bg="Green")
            self.check_var = False
    
        else:
            ent.configure(bg="White")
            self.check_var = True
    

    ...你的按钮是:

    self.button_check = tk.Button(text="✅", height= 1,command=lambda x=self.entry1: self.check(x))
    

    另外,我希望您有充分的理由使用place,因为在这种情况下,使用grid 可以让您的生活更轻松。

    更多解释请阅读:Tkinter assign button command in loop with lambda

    【讨论】:

    • 谢谢,但现在我为绿色背景定义的变量不能按计划工作。因此,当我检查第一个条目并检查第二个条目时,我需要单击 2 次才能将其变为绿色
    • @antal 因为每次单击按钮时,global self.check_var 的值都会发生变化。您必须想出更好的方法,我认为最好为此提出一个新问题
    猜你喜欢
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多