python-3.x - 从其他功能更改条目小部件值
问题描述
我在使用 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)
解决方案
您的代码中需要修复一些小问题。我在下面添加了一个带有评论的工作示例。
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()
推荐阅读
- javascript - 如何将 php 数组设置为 html 元素数据属性作为 javascript 数组?
- php - Laravel 5.7 - 如何在用户未登录时显示电子邮件验证重定向页面?
- laravel - Laravel 中的复杂关系(hasManyThrough 通过数据透视表)
- java - 本地集群中的服务结构 java 应用程序部署失败
- java - Singleton 中上下文类型为 TRANSACTION 的 EntityManager 会加入外部 bean 管理的事务吗?
- typescript - 使用 Array 和 TypedArray 在 Typescript 中重载递归函数
- php - 作曲家安装 Symfony 3.4 - bootstrap.php.cache
- visual-studio-code - 将终端面板移至底部选项消失了吗?(VS代码)
- python-2.7 - 在 MainPage 中使用 POST 方法的 Google App Engine Python
- javascript - Vue - 如何在 v-if 或组件中使用窗口对象