Случайное открытие окна tkinter в операторе if / else - PullRequest
0 голосов
/ 25 марта 2020

Мне интересно, правильно ли я понял утверждение if else или это проблема tkinter. Я хочу, чтобы, если в любом или во всех полях оставлено 0, выдается сообщение об ошибке. Но после закрытия сообщения об ошибке открывается случайное пустое окно. Это мой код Специфическая c область - это оператор if else внутри функции valueget ()

import tkinter as tk

def mainwindow():    
    mainwindow = tk.Tk()
    mainwindow.title('Enter values')
    mainwindow.geometry('160x110')
    mainwindow.config(bg='#aaf0d1')

    tk.Label(mainwindow, text = 'Enter a', font = ('verdana'),  bg='#aaf0d1').grid(row=0)
    tk.Label(mainwindow, text = 'Enter b', font = ('verdana'),  bg='#aaf0d1').grid(row=1)
    tk.Label(mainwindow, text = 'Enter c', font = ('verdana'),  bg='#aaf0d1').grid(row=2)

    getA = tk.IntVar()
    aBox = tk.Entry(mainwindow, textvariable = getA, width=3,  bg='#aaf0d1')
    aBox.grid(row=0, column=1)
    aBox.config(highlightbackground='#aaf0d1')                

    getB = tk.IntVar()
    bBox = tk.Entry(mainwindow, textvariable = getB, width=3,  bg='#aaf0d1')
    bBox.grid(row=1, column=1)
    bBox.config(highlightbackground='#aaf0d1')

    getC = tk.IntVar()
    cBox = tk.Entry(mainwindow, textvariable = getC, width=3,  bg='#aaf0d1')
    cBox.grid(row=2, column=1)
    cBox.config(highlightbackground='#aaf0d1')

    button = tk.Button(mainwindow, text='Obtain roots', command = lambda: valueget(), font = ('verdana'), highlightbackground='#aaf0d1')
    button.grid(row=4)
    button.config(bg='#aaf0d1')

    def valueget():    

        readA = getA.get()
        readB = getB.get()
        readC = getC.get()


        intA = int(readA)
        intB = int(readB)
        intC = int(readC)

        negroot = (readB**2)-(4*readA*readC)

        quadformulaplus = (-readB + (pow(negroot,0.5)))/(2*readA) #quad forumla
        quadformulaminus = (-readB - (pow(negroot,0.5)))/(2*readA) #quad forumla



        messagewindow = tk.Tk()
        messagewindow.geometry('290x50')
        messagewindow.title('Roots of the equation')
        messagewindow.config(bg='#aaf0d1')


        if readA == 0 or readB==0 or readC==0 or (readA==0 and readB==0 and readC==0):
            errorwindow = tk.messagebox.showerror(message='none').pack()
        else:                  
            label = tk.Label(messagewindow, text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}', bg='#aaf0d1', font = ('verdana'))
            label.grid(row=1)
            closebutton = tk.Button(messagewindow, text='Close', command = lambda: messagewindow.destroy(), font = ('verdana'), highlightbackground='#aaf0d1')
            closebutton.grid(row=2)
            closebutton.config(bg='#aaf0d1')

            messagewindow.mainloop()

   # print(f'the roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}')
mainwindow.mainloop()


def startup():
    startpage = tk.Tk()
    startpage.title('Solver')
    photo = tk.PhotoImage(file = r"/Users/isa/Desktop/DiffEqns/cover.png")  #image load
    coverbutton = tk.Button(startpage, image = photo, command = lambda: [startpage.destroy(), mainwindow()])
    coverbutton.pack()
    coverbutton.configure(highlightbackground='#aaf0d1')
    startpage.mainloop()

startup()

Ответы [ 2 ]

0 голосов
/ 25 марта 2020

Вот базовое c представление о том, что я буду делать:

import tkinter as tk
from tkinter import messagebox

def mainwindow(root):
    # Creates a toplevel window
    mainwindow = tk.Toplevel()
    mainwindow.protocol("WM_DELETE_WINDOW", root.destroy) # This overrides the "X" being clicked to also destroy the root window.
    root.withdraw() # "Hides" the root window, leaving it (and mainloop) running in the background.
    mainwindow.title('Enter values')
    mainwindow.geometry('160x110')
    mainwindow.config(bg='#aaf0d1')

    # Since all three of the labels/entries are the same
    # we can save space by generating them in a loop
    entry_items = ('Enter a', 'Enter b', 'Enter c')
    values = []
    for x, item in enumerate(entry_items): # Using enumerate and x to assign rows
        tk.Label(mainwindow, text = item,
                 font = ('verdana'),  bg='#aaf0d1').grid(row=x) # Row assigned to x.

        values.append(tk.StringVar()) # Appended StringVar to list.
        tk.Entry(mainwindow,
                 textvariable = values[-1], # Uses the last value appended to the values list.
                 highlightbackground='#aaf0d1',
                 width=3,
                 bg='#aaf0d1').grid(row=x, column=1) # Row assigned to x.     

    tk.Button(mainwindow,
              text='Obtain roots',
              command = lambda vals = values: valueget(vals), # Here the button command is assigned with the values list
              font = ('verdana'), bg='#aaf0d1',
              highlightbackground='#aaf0d1').grid(row=3) # we know there are 3 items before this.

    mainwindow.lift() # This is a method of bringing a window to the front

def valueget(vals):
    # This line gets the values from the StringVars, converts them to ints,
    # and returns them to their respective variables.
    try:
        readA, readB, readC = [int(val.get()) for val in vals]
    except ValueError:
        messagebox.showerror(title="Number Error", message='Values must be numbers')
        return

    # Here the variables are checked to see if they are 0
    # Since each one is being checked if it is 0, there is no need to check if they are all 0.
    for val in (readA, readB, readC):
        if val == 0:
            # If they are 0, shows an error message
            messagebox.showerror(title="Zero Error", message='Values must not be zero')
            return

    # Creates a toplevel to display the results
    messagewindow = tk.Toplevel()
    messagewindow.title('Roots of the equation')
    messagewindow.config(bg='#aaf0d1')

    negroot = (readB**2)-(4*readA*readC)

    quadformulaplus = (-readB + (pow(negroot,0.5)))/(2*readA) #quad forumla
    quadformulaminus = (-readB - (pow(negroot,0.5)))/(2*readA) #quad forumla

    tk.Label(messagewindow,
             text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}',
             bg='#aaf0d1',
             font = ('verdana')).pack(padx = 5, pady = 2)

    tk.Button(messagewindow,
              text='Close',
              command = messagewindow.destroy, # There is no need for a lambda for this.
              font = ('verdana'),
              bg = '#aaf0d1',
              highlightbackground='#aaf0d1').pack(padx = 5, pady = 2)

    # print(f'the roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}')

    messagewindow.lift() # This is a method of bringing a window to the front

def startup():
    startpage = tk.Tk()
    startpage.title('Solver')
    # COMMENTED OUT FOR TESTING
    #photo = tk.PhotoImage(file = r"/Users/isa/Desktop/DiffEqns/cover.png")  #image load
    coverbutton = tk.Button(startpage,
                            # COMMENTED OUT FOR TESTING
                            #image = photo,
                            text = "TESTING", # HERE FOR TESTING
                            highlightbackground='#aaf0d1',
                            command = lambda root = startpage: mainwindow(root)).pack() # Passes the startpage to the mainwindow function.

    startpage.mainloop() # The only mainloop you need.

startup()
0 голосов
/ 25 марта 2020

Я бы порекомендовал улучшить читаемость оператора if-else для начала.

coefficients = [readA, readB, readC]
if sum(coefficients):        # If they all are all zeros this will be False
    if min(coefficients):    # If any one is zero, this will be False
        label = tk.Label(messagewindow, text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}', bg='#aaf0d1', font = ('verdana'))
        label.grid(row=1)
        closebutton = tk.Button(messagewindow, text='Close', command = lambda: messagewindow.destroy(), font = ('verdana'), highlightbackground='#aaf0d1')
        closebutton.grid(row=2)
        closebutton.config(bg='#aaf0d1')
    else:
        errorwindow = tk.messagebox.showerror(message='none').pack()
else:
    errorwindow = tk.messagebox.showerror(message='none').pack()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...