我開始使用 tkinter 和類方法進行編碼。我嘗試撰寫一個待辦事項串列,我可以通過按下條目下方的按鈕來創建多個條目。如果按下,條目旁邊的按鈕應更改條目的顏色。現在的問題是,當我創建多個條目時,按鈕只會更改最新的條目。所以我的問題是如何在創建時指定條目?
Sry 對于明顯的錯誤,我是編碼新手: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()
uj5u.com熱心網友回復:
您正在改變bg的self.entry1其不斷每個條目創建時間覆寫本身,按鈕被點擊,所以當,它始終是最后一個條目。最簡單的解決方案是定義一個引數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 使用 lambda 回圈分配按鈕命令
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/401000.html
