简体   繁体   English

使用 Tkinter 将图像添加到顶层 window 将显示在主窗口中

[英]Adding image to Toplevel window using Tkinter is getting displayed in Mainwindow instead

I am trying to add an image to the toplevel window instead of which the image displays in the main window.我正在尝试将图像添加到顶层 window,而不是图像显示在主 window 中。 There is a entry text box (int value) in the toplevel window whose value is not getting updated on user entry (always set to 0).在顶层 window 中有一个输入文本框(int 值),其值不会在用户输入时更新(始终设置为 0)。

MainWindow -> Main/Parent window, VerbWindow -> Toplevel window MainWindow -> Main/Parent window, VerbWindow -> Toplevel window

I would pls request someone to help me.我会请人帮助我。

Below is my code:下面是我的代码:

#Mainwindow

from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
from gui.verb_window import *

class MainWindow():
    def __init__(self,master):
        self.master=master

        ### label display
        self.main_label = Label(self.master, text="What would you like to learn???", font="Arial 15 bold")
        self.main_label.pack(fill=X, pady=15)

        ### Image display

        self.image = Image.open("learn_german.jpg")
        self.photo = ImageTk.PhotoImage(self.image)
        self.pic_lab = Label(image=self.photo)
        self.pic_lab.pack(side=LEFT, anchor='nw', pady=15)

        ### Combo box

        self.learn_combo = StringVar()
        self.learn_combo_value = ttk.Combobox(self.master, width=30, textvariable=self.learn_combo)
        # Adding combobox drop down list
        self.learn_combo_value['values'] = (' Nouns',
                                            ' Verbs',
                                            ' Prepositions',
                                            ' Adjectives')

        self.learn_combo_value.pack(pady=30)

        ### Button

        self.go_button=Button(self.master,text="Let's Go!",font="Arial 15",command=self.click_go)
        self.go_button.pack(ipadx=10,ipady=10)

    def click_go(self):
        """Let's Go button functionality"""
        print(f"You have selected {self.learn_combo.get()}")

        if ((self.learn_combo.get()).lower()).strip()==("Verbs".lower()).strip():
            print("hello")
            verb_win_obj=VerbWindow()


def main():
    root=Tk()
    mainwin = MainWindow(root)
    root.title("VocabsEasy!")
    root.geometry("600x350")
    root.wm_iconbitmap("icon_pic_study.ico")
    root.mainloop()

if __name__ == '__main__':
    main()
#VerbWindow

from tkinter import *
from tkinter import ttk
from gui import *
from PIL import Image,ImageTk

class VerbWindow(Toplevel):

    def __init__(self):
        Toplevel.__init__()
        self.geometry("700x400")
        self.title("Verbs")
        self.wm_iconbitmap("icon_pic_study.ico")

        self.verbTargetImage()
        self.displayTargetLabel()
        self.inputTargetTextbox()


    def displayTargetLabel(self):
        """Asks you to set target for today"""
        self.target_label = Label(self, text="How many verbs would you like to learn today???", font="Arial 13")
        self.target_label.pack(fill=X, pady=15)

    def click_go_learn(self):
        """Go Learn button functionality"""
        print(f"No. of verbs to be learnt {self.target.get()}")

    def inputTargetTextbox(self):
        """Gets input from the user"""
        self.target=IntVar()
        self.target_entry=Entry(self,textvariable=self.target,width=10)
        self.target_entry.pack(pady=20)

        self.go_button = Button(self, text="Go learn!", font="Arial 15",command=self.click_go_learn)
        #self.go_button.pack(ipadx=10, ipady=8)
        self.go_button.place(x=550,y=150)
        print(f"No. of verbs to be learnt hereeeeeeeeeeee {self.target.get()}")


    def verbTargetImage(self):
        """Image display in the main window"""
        # verb_win = Toplevel(self)
        global photo_target
        self.image_child=Image.open("set_target.jpg")
        print("hallo1")
        photo_target=PhotoImage(self.image_child)
        print("hallo2")

        try:

            self.pic_lab=Label(image=photo_target)
            self.pic_lab.pack(self,side=LEFT,anchor='nw',pady=15)
            # self.pic_lab.image=self.photo

        except Exception as e:
            print(e)

You haven't specified the parent of the label, by default it assumes the root ( MainWindow ) as the parent.您尚未指定 label 的父级,默认情况下它假定根 ( MainWindow ) 作为父级。 The below should work.下面应该工作。

self.pic_lab=Label(self, image=photo_target)

EDIT编辑

On closely inspecting the code, I found couple of other issues在仔细检查代码时,我发现了其他几个问题

  • You can't pass Image.open() instance to tkinter PhotoImage , if you plan to use tkinter PhotoImage then pass the path directly or if you wish to use PIL then pass the Image.open() instance to ImageTk.PhotoImage()您不能将Image.open()实例传递给tkinter PhotoImage ,如果您打算使用tkinter PhotoImage然后直接传递路径,或者如果您希望使用PIL然后将Image.open()实例传递给ImageTk.PhotoImage()
  • You have added self in the pack statement.您已在pack语句中添加了self

Your final code of verbTargetImage function should look something like this您的verbTargetImage function 的最终代码应如下所示

def verbTargetImage(self):
    """Image display in the main window"""
    # verb_win = Toplevel(self)
    global photo_target
    self.image_child=Image.open("favicon.png")
    print("hallo1")
    photo_target=ImageTk.PhotoImage(self.image_child)
    print("hallo2")

    try:
        self.pic_lab=Label(self,image=photo_target)
        self.pic_lab.pack(side=LEFT,anchor='nw',pady=15)
        # self.pic_lab.image=self.photo

    except Exception as e:
        print(e)

There is a entry text box (int value) in the toplevel window whose value is not getting updated on user entry (always set to 0).在顶层 window 中有一个输入文本框(int 值),其值不会在用户输入时更新(始终设置为 0)。

I am not able to reproduce this, I believe it is working as expected, here is the print that I get when I enter 5 and click Go learn!我无法重现这个,我相信它按预期工作,这是我输入5并单击Go learn! button按钮

No. of verbs to be learnt 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM