文本在错误的窗口中打开

时间:2018-08-18 10:05:24

标签: python tkinter

我正在尝试将文本插入新窗口,并在用户单击按钮时打开。但是,当我尝试这样做时,要在新窗口中打开的文本框会在第一个窗口中打开。参见下图:

Image of where text is in the wrong window

我已经完成了研究,遇到的一个答案是我多次共享“ Tk”小部件。

这是我的代码

from tkinter import *
import tkinter as tk

root = tk.Tk()

text = Text(root, height=4, width=100)
text.pack()
text.insert(END, "The family car starting price is £24060 including VAT and 
CO2 taxes")
text.insert(END, "\nThe sports car starting price is £30115 including VAT 
and CO2 taxes")
text.insert(END, "\nThe suv car starting price is £36100 including VAT and 
CO2 taxes")

def family_create_window():
    window = tk.Toplevel(root)
    window.title("family Exterior colour")

    text = Text(root, height=4, width=100)
    text.pack()
    text.insert(END, "Hello")

    def newwindow():
        window = tk.Toplevel(root)
        window.title("New window")

    greyex = PhotoImage(file="vwfamilygrey.png")
    greyexlabel = Button(window, image=greyex)
    greyexbutton = Button(window, image=greyex, command=newwindow)
    greyexbutton.pack()
    window.mainloop()

familycar = PhotoImage(file = "VW family car.png")
familylabel = Button(root, image=familycar)
familybutton = Button(root, image=familycar, command=family_create_window)

familybutton.pack()
root.mainloop()

用户单击家用车的图像后,我想做的是打开一个新窗口,其中带有图像的新窗口打开,窗口顶部带有文本“ hello”。

“ greyex”是外部颜色,可提供其他帮助。

任何帮助表示赞赏。谢谢

1 个答案:

答案 0 :(得分:1)

Text小部件的父小部件切换为“你好”,从rootwindow。这将使“文本”窗口小部件显示在新窗口中,而不是在主窗口中。

示例:

def family_create_window():
    window = tk.Toplevel(root)
    window.title("family Exterior colour")

    text = Text(window, height=4, width=100)  # Switch root to window
    text.pack()
    text.insert(END, "Hello")

希望我能帮忙