python - 图像仅显示在第一个按钮上
问题描述
代码是这样的,当我单击带有图像的按钮时。第二个按钮必须添加到窗口中。但是当我单击按钮时,第二个按钮上没有相同的图像。
(main.py)
from tkinter import *
import second
def main():
root = Tk()
first(root)
# first UI
class first:
def __init__(self, root):
self.root = root
self.root.title("Demo UI")
self.root.geometry("500x500")
# sample button
photo = PhotoImage(file="rot13.png")
btn = Button(root, image=photo, command=self.switch)
btn.pack()
self.root.mainloop()
def switch(self):
second.newUI(self.root)
return None
pass
# run the program
main()
(第二个.py)
from tkinter import *
class newUI:
def __init__(self, root):
self.root = root
# sample button
photo = PhotoImage(file="rot13.png")
btn = Button(root, image=photo)
btn.pack()
pass
解决方案
检查这个。参数是对当前类实例的self
引用,用于访问属于该类的变量。所以我基本上引用了所有内容,因此您可以在类中的任何位置调用小部件。
from tkinter import *
import fff
def main():
root = Tk()
first(root)
# first UI
class first:
def __init__(self, root):
self.root = root
self.root.title("Demo UI")
self.root.geometry("500x500")
# sample button
self.photo = PhotoImage(file="rot13.png") #=== create a reference of the image
self.btn = Button(self.root, image=self.photo, command=self.switch)
self.btn.pack()
self.root.mainloop()
def switch(self):
fff.newUI(self.root,self.photo) #=== Added photo parameter
pass
# run the program
main()
fff.py icon参数是图片的路径
from tkinter import *
from PIL import ImageTk
class newUI:
def __init__(self, master,icon,*args):
self.icon = icon #=== Image Path added from the main file
self.root = master
# ===sample button
self.btn = Button(master, image=self.icon) #== Image
self.btn.pack()
推荐阅读
- c++ - 使用 const bool 删除调试信息时的编译器优化
- angular - 将数据从一个组件发送到另一个组件
- python - Python:如何用网络抓取表的第一行替换标题
- c# - 在 WPF-App 中集成帮助的选项
- c - 使用 sqlite3_exec() 在 C 中获取单个结果
- python - 无法使用 Instaloader 和 tkinter 下载图像
- android - 从通知中取消或暂停下载
- java - 检查传递给 Java 泛型的对象类
- sql - 编写 T-SQL 查询以查找至少连续出现 3 次的所有数字
- c++ - Cython unsigned char uuid_t[16] 表示