文本在错误的窗口中打开

2024-10-03 00:21:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将文本插入到一个新窗口中,该窗口在用户单击按钮时打开。但是,当我尝试此操作时,我想在新窗口中打开的文本框将在第一个窗口中打开。见下图:

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”是额外帮助的外部颜色

谢谢你的帮助。谢谢


Tags: textimageisbuttonrootwindowcarfamily
1条回答
网友
1楼 · 发布于 2024-10-03 00:21:58

Text小部件的父小部件root切换到window,该小部件会说“你好”。这将使文本小部件显示在新窗口而不是主窗口上

例如:

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")

希望我能帮忙

相关问题 更多 >