Tkinter中的背景和按钮问题/问题

时间:2017-10-22 18:14:22

标签: python tkinter

我正在为我们的项目设计一个GUI。我的主屏幕设置有背景,但是当程序启动时,会弹出一个随机的小窗口,我不知道为什么。另外,如何在下拉菜单中创建一个附加到按钮的新窗口?

我的代码:

from tkinter import Tk, BOTH, RIGHT, RAISED, Menu
from tkinter.ttk import Frame, Button, Style

from tkinter import *
from tkinter import messagebox

    class Main(Frame):
        top = Tk()

        C = Canvas(top, bg="blue", height=700, width=450)
        filename = PhotoImage(file="C:\\Users\\Owner\\Pictures\\Saved Pictures\\Jupiter.png")
        background_label = Label(top, image=filename)
        background_label.place(x=0, y=0, relwidth=1, relheight=1)

        C.pack()
        top.mainloop

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.master.title("Project Astronomical-Yearly-Location-Apparatus")
        self.pack(fill=BOTH, expand=1)
        self.centerWindow()

        self.master.title("Buttons")
        self.style = Style()
        self.style.theme_use("default")

        frame = Frame(self, relief=RAISED, borderwidth=1)
        frame.pack(fill=BOTH, expand=True)

        self.pack(fill=BOTH, expand=True)

        nextButton = Button(self, text="Next")
        nextButton.pack(side=RIGHT)

        backButton = Button(self, text="Back")
        backButton.pack(side=RIGHT)

        recordButton = Button(self, text="Record")
        recordButton.pack(side=RIGHT)

        self.master.title("Commence")

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Top View", command=self.initUI)
        fileMenu.add_command(label="Bye Felicia", command=self.onExit)
        menubar.add_cascade(label="Commence", menu=fileMenu)


    def onExit(self):
        self.quit()

    def centerWindow(self):
        w = 1036
        h = 720

        sw = self.master.winfo_screenwidth()
        sh = self.master.winfo_screenheight()

        x = (sw - w) / 2
        y = (sh - h) / 2
        self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))


def main():
    root = Tk()
    ex = Main()
    root.mainloop()


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

如布莱恩和伊桑所说,你有

root = Tk() # This creates a blank window
ex = Main() # This creates a window from the Top = Tk() line in your Main class

要使按钮打开一个全新的窗口,请尝试以下操作:

    nextButton = Button(self, text="Next", command = self.newWindow)
    nextButton.pack(side=RIGHT)    

你必须在Main类中定义一个名为newWindow的函数,如下所示:

 def newWindow(self):
    myNewWindow = Toplevel() # Toplevel() makes a new window pop to the front of the screen
    # Now you can add stuff to this new window
    newButton = Button(myNewWindow, text="Press me to close this new window!", command = myNewWindow.destroy) # destroy() is a function built into Toplevel that should close the window
    newButton.pack()