首页 > 解决方案 > 从其他功能更改条目小部件值

问题描述

我在使用 tkinter 编程方面非常陌生,尤其是在课程方面。如何制作一个从同一类运行功能并更改条目小部件的按钮。在我的代码中,每当单击 button1 并且文件路径函数运行时,我都想更改 entry1。

感谢您的帮助。

Class Example(Frame):

    def __init__(self):
        super().__init__()
        self.initUI()

    def filepath():
        filename = fd.askopenfilename()
        entry1.delete(0,END)
        entry1.insert(0,filename)

    def initUI(self):

        self.master.title("EFEKTYWNOŚĆ APP")
        self.pack(fill=BOTH, expand=True)

        cd = (os.getcwd())

        frame1 = Frame(self)
        frame1.pack(side = LEFT)

        lbl1 = Label(frame1, 
                     text="...",
                     wraplength = 250 )
        lbl1.pack(side=LEFT, padx=5, pady=5)

        path = os.path.join(cd, 'ico', '...')
        photo = PhotoImage(file = path)
        cphoto = photo.subsample(4,4)
        button1  = Button(frame1,
                          text='WYBIERZ PLIK',
                          image = cphoto,
                          compound = LEFT, 
                          command = Example.filepath)
        button1.image = cphoto
        button1.pack(side=LEFT, fill = Y, padx=5, pady=5)

        entry1 = Entry(frame1)
        entry1.pack(side=LEFT, fill = Y, padx=5, pady=5)

标签: python-3.xclasstkinter

解决方案


您的代码中需要修复一些小问题。我在下面添加了一个带有评论的工作示例。

from tkinter import *
from tkinter import filedialog as fd
import os

class Example(Frame):

    def __init__(self, master,**kwargs): #have your Frame accept parameters like how a normal frame should
        super().__init__(master,**kwargs)
        self.master = master #set master as an attribute so you can access it later
        self.initUI()

    def filepath(self): #add self to make the method an instance method
        filename = fd.askopenfilename()
        self.entry1.delete(0, END) #use self when referring to an instance attribute
        self.entry1.insert(0, filename)


    def initUI(self):
        self.master.title("EFEKTYWNOŚĆ APP")
        self.pack(fill=BOTH, expand=True)

        cd = (os.getcwd())

        frame1 = Frame(self)
        frame1.pack(side=LEFT)

        lbl1 = Label(frame1,
                     text="...",
                     wraplength=250)
        lbl1.pack(side=LEFT, padx=5, pady=5)

        path = os.path.join(cd, 'ico', '...')
        photo = PhotoImage(file=path)
        cphoto = photo.subsample(4, 4)
        button1 = Button(frame1,
                         text='WYBIERZ PLIK',
                         image=cphoto,
                         compound=LEFT,
                         command=self.filepath) #refer to instance methods by self.your_method
        button1.pack(side=LEFT, fill=Y, padx=5, pady=5)

        self.entry1 = Entry(frame1) #add self to make it an instance attribute
        self.entry1.pack(side=LEFT, fill=Y, padx=5, pady=5) #you will then need to use self.entry1 within your class instance

root = Tk()
Example(root)
root.mainloop()

推荐阅读