【问题标题】:How to open a new window which is in another class in tkinter如何在 tkinter 中打开另一个类中的新窗口
【发布时间】:2022-01-19 10:35:00
【问题描述】:
import tkinter as tk
from tkinter import *
import PIL
from PIL import Image
from PIL import ImageTk, Image
import time


class Sharingan(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry("60x60+1465+750")
        self.config()

        self.photo_sharingan = ImageTk.PhotoImage(file="sharingan.png")

#this button has to open a new window on button click:     
        self.btn_sharingan = Button(image=self.photo_sharingan, bd=0,
                                    command=lambda: [self.change_btn_img(),self.open_main_window()])
        self.btn_sharingan.place(x=-3, y=-4)

        self.photo_sharingan2 = ImageTk.PhotoImage(file="sharingan-2.png")
        self.btn_sharingan2 = Button(image=self.photo_sharingan2, bd=0, command=lambda: [self.change_btn_img2()],
                                     highlightbackground="black")
        self.btn_sharingan2.place_forget()

        self.overrideredirect(True)

    def change_btn_img(self):
        self.btn_sharingan.place_forget()
        self.btn_sharingan2.place(x=-3, y=-4)

    def change_btn_img2(self):
        self.btn_sharingan2.place_forget()
        self.btn_sharingan.place(x=-3, y=-4)

#this is the function but how do I make it to initialize and mainloop class-MainWindow
def open_main_window():
    

class MainWindow(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry("200x100")



app1 = Sharingan()
app1.mainloop()

所以基本上我想通过单击按钮打开一个新窗口,其代码在另一个类中。此按钮在 class1 中。我怎样才能完成这个?功能是“open_main_window”,按钮是“sharingan”。我只想在单击此按钮时打开一个新窗口我应该在函数中编写什么代码?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    要打开一个新窗口,您可以使用tk.Toplevel(),因此您的功能是:

    def open_main_window(self):
       self.newWindow = tk.Toplevel()
    

    有关tk.Toplevel()的更多信息,请查看this tutorial

    【讨论】:

    • 真的很有帮助,非常感谢
    • 那么现在如何将小部件添加到该新窗口。
    • 您是在尝试从open_main_window 函数还是在其他函数中添加小部件/小部件?
    • 没问题,如果您对主要问题的原始答案感到满意,您是否可以单击勾号表示您已接受它。我会尝试找到一些可能有帮助的教程。
    猜你喜欢
    • 2018-05-11
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2022-08-23
    相关资源
    最近更新 更多