Если в окне tkinter много меток, как их идентифицировать по отдельности? - PullRequest
0 голосов
/ 01 ноября 2019

В моем приложении с графическим интерфейсом. Есть два окна (главное окно и верхний уровень). В главном окне у меня есть кнопка, названная как метка. Если пользователь нажмет на нее, метка будет сформирована в окне верхнего уровня. Например, если он щелкнет4 раза на этой кнопке, 4 метки будут сформированы в окне верхнего уровня. Я связываю среднюю кнопку мыши с этой меткой, если он щелкает свойства этой метки (в окне Toplevel), которые будут отображаться в главном окне. Мой вопрос заключается в том, как определить, чтопользователь щелкнул по какой метке и соответственно обновил эту метку.

class Frame2:
    def __init__(self,root):
        self.list=["label","Button","Entry","Text","Frame","RadioButton","Checkbutton","Canvas","LabelFrame","Notebook","ScaleWidget"]
        self.w2=root
        self.w2.state('zoomed')
        self.w2.title("IDE")
        self.w2.configure(background="white")
        self.projectwindow()
        self.tools()
        #=============
    def projectwindow(self):
        self.workingarea=Toplevel(self.w2)
        self.workingarea.geometry('930x660+5+25')
        #================
    def tools(self):
        self.prop=ttk.Notebook(self.w2,width=self.w2.winfo_screenwidth()-int(self.w2.winfo_screenwidth()*0.7),height=self.w2.winfo_screenheight())
        self.prop.place(x=self.w2.winfo_screenwidth()-int(self.w2.winfo_screenwidth()*0.3),y=0)
        self.widgets=Frame(self.prop,bg="white")
        self.root_properties=Frame(self.prop,bg="white")
        self.properties=Frame(self.prop)
        self.prop.add(self.widgets,text='Widgets',compound=TOP)
        self.prop.add(self.root_properties,text='Root Window Properties',compound=TOP)
        self.prop.add(self.properties,text='Properties',compound=TOP)
        #=========
        self.widget_section=LabelFrame(self.widgets,text='TK Widgets',padx=5,pady=15,bg='white')
        self.widget_section.place(x=10,y=10)
        self.obj=labels(self.workingarea,self.properties)
        for self.i in range(11):
            self.btn_widgets=Button(self.widget_section,text=self.list[self.i], borderwidth=2, relief="groove",width=33,font=("",14,""),command=self.obj.label)
            self.btn_widgets.grid(row=self.i,column=0,pady=2)
        #=====================
        self.title="Tkinter"
        self.bgcolor="white"
        self.geometry="930x660+5+25"
        self.var=StringVar(self.root_properties)
        self.var.set("True")
        #===========
        self.lbl_title=Label(self.root_properties,text="Title",font=("",13,""),anchor="w",width=18,bg="white")
        self.lbl_title.place(x=10,y=10)
        self.lbl_bgcolor=Label(self.root_properties,text="Background Colour",font=("",13,""),width=18,anchor="w",bg="white")
        self.lbl_bgcolor.place(x=10,y=50)
        self.ety_title=Entry(self.root_properties,font=("",13,""), borderwidth=2, relief="groove")
        self.ety_title.place(x=190,y=10)
        self.ety_bgcolor=Entry(self.root_properties,font=("",13,""), borderwidth=2, relief="groove")
        self.ety_bgcolor.place(x=190,y=51)
        self.lbl_bghint=Label(self.root_properties,text="Mention background color \nas name or in hexadecimal",width=25,bg="white")
        self.lbl_bghint.place(x=190,y=75)
        self.lbl_resize=Label(self.root_properties,text="Resizable",font=("",13,""),anchor="w",width=18,bg="white")
        self.lbl_resize.place(x=10,y=110)
        self.opt_menu=OptionMenu(self.root_properties, self.var, "True", "False")
        self.opt_menu.config(width=24, relief="groove",bg="white",highlightthickness=0)
        self.opt_menu.place(x=190,y=117)
        self.lbl_geometry=Label(self.root_properties,text="Geometry",font=("",13,""),anchor="w",width=18,bg="white")
        self.lbl_geometry.place(x=10,y=170)
        self.ety_geom=Entry(self.root_properties,font=("",13,""), borderwidth=2, relief="groove")
        self.ety_geom.place(x=190,y=170)
        self.geomhint=Label(self.root_properties,text="Mention Geometry in axb format.\nEg :  400x500",width=25,bg="white")
        self.geomhint.place(x=190,y=200)
        self.btn_run=Button(self.widgets,text="Run",command=self.write, borderwidth=2, relief="groove",width="20",bg="white")
        self.btn_run.place(x=150,y=650)

#==========This is a separate file label.py======================
from tkinter import *
from dnd import *
class labels:
    def __init__(self,root,prop):
        self.root=root
        self.prop=prop
        self.counter=1
    #=========================
    def fcounter(self):
        self.counter+=1
    #-----------------
    def label(self):
        self.name_var="label"+str(self.counter)
        self.name_var=Label(self.root,text='Label'+str(self.counter))
        self.name_var.pack()
        self.name_var.bind("<Button-2>",self.lbl_property)
        make_draggable(self.name_var)
        self.fcounter()
    def lbl_property(self,event):
        #====================
        self.lbl_variable=Label(self.prop,text="Variable",font=("",13,""),anchor="w",width=18,bg="white")
        self.lbl_variable.place(x=10,y=10)
        self.lbl_bgcolor=Label(self.prop,text="Background Color",font=("",13,""),anchor="w",width=18,bg="white")
        self.lbl_bgcolor.place(x=10,y=50)
        self.lbl_fgcolor=Label(self.prop,text="Text Color",font=("",13,""),width=18,anchor="w",bg="white")
        self.lbl_fgcolor.place(x=10,y=90)
        self.lbl_width=Label(self.prop,text="Width",font=("",13,""),anchor="w",width=18,bg="white")
        self.lbl_width.place(x=10,y=130)
        self.lbl_height=Label(self.prop,text="Height",font=("",13,""),anchor="w",width=18,bg="white")
        self.lbl_height.place(x=10,y=170)
        self.lbl_anchor=Label(self.prop,text="Anchor",font=("",13,""),anchor="w",width=18,bg="white")
        self.lbl_anchor.place(x=10,y=210)

        #======================
        self.loc_var1=StringVar(self.prop)
        self.loc_var1.set("CENTER")
        self.bgcolor="white"
        self.fgcolor="black"
        self.width=1
        self.height=1
        #==========================
        self.ety_variable=Entry(self.prop,font=("",13,""), borderwidth=2, relief="groove")
        self.ety_variable.place(x=190,y=10)
        self.ety_variable.insert(0,self.name_var)
        self.ety_bgcolor=Entry(self.prop,font=("",13,""), borderwidth=2, relief="groove")
        self.ety_bgcolor.place(x=190,y=50)
        self.ety_fgcolor=Entry(self.prop,font=("",13,""), borderwidth=2, relief="groove")
        self.ety_fgcolor.place(x=190,y=90)
        self.ety_width=Entry(self.prop,font=("",13,""), borderwidth=2, relief="groove")
        self.ety_width.place(x=190,y=130)
        self.ety_height=Entry(self.prop,font=("",13,""), borderwidth=2, relief="groove")
        self.ety_height.place(x=190,y=170)
        self.opt_anchor=OptionMenu(self.prop,self.loc_var1,"CENTER","N","S","W","E","NE","NW","SW","SE")
        self.opt_anchor.config(width=24, relief="groove",bg="white",highlightthickness=0)
        self.opt_anchor.place(x=190,y=210)
    #===========
        self.btn_apply=Button(self.prop,text="Apply",command=self.apply, borderwidth=2, relief="groove",width="20",bg="white")
        self.btn_apply.place(x=150,y=650)
    #=================
    def apply(self):
        if self.ety_bgcolor.get()!="":
            self.bgcolor=self.ety_bgcolor.get()
        if self.ety_fgcolor.get()!="":
            self.fgcolor=self.ety_fgcolor.get()
        if self.ety_width.get()!="":
            self.width=self.ety_width.get()
        if self.ety_height.get()!="":
            self.height=self.ety_height.get()
        self.name_var.configure(bg=self.bgcolor,fg=self.fgcolor,width=self.width,height=self.height)

1 Ответ

0 голосов
/ 01 ноября 2019

Если вы используете bind, то оно отправляет событие и имеет event.widget, который дает вам доступ к нажатой кнопке.

Если вы используете command=, когда вы можете назначить функцию после создания кнопки и использовать этокнопка в качестве аргумента в функции

my_button = tk.Button(...)
my_button["command"] = lambda: my_function(my_button)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...