首页 > 解决方案 > 图像仅显示在第一个按钮上

问题描述

代码是这样的,当我单击带有图像的按钮时。第二个按钮必须添加到窗口中。但是当我单击按钮时,第二个按钮上没有相同的图像。

(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

结果:[1]:https ://i.stack.imgur.com/3HFL1.png

标签: pythontkinter

解决方案


检查这个。参数是对当前类实例的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()


推荐阅读