Python код tkinter работает в цикле, нужна помощь, чтобы закрыть его - PullRequest
0 голосов
/ 10 мая 2019

У меня есть код Python, который создает окно GUI с использованием tkinter, и у него есть некоторые фоновые задачи, которые запускаются в фоновом режиме при нажатии кнопки «Выполнить».

Но мне пришлось запускать программу, пока она называется.Для запуска фоновых данных мне нужно было либо использовать команду root.mainloop (), либо использовать root.after ().

Но root.after () можно использовать только один раз, и мне придется подождать, пока определенное количество времени будет предоставлено для ввода, а не до выполнения фоновых задач.

Поэтому я поместил код в цикл, чтобы снова и снова перезапускать root, пока вызывается run.Это прекрасно работает.Но я не знаю, как закрыть окно.

Я пытался использовать root.destroy (), но это не работает.

System.exit () завершает работу всей программы, и это также не работает.

Пожалуйста, помогите мне с кодом

import tkinter as tk
from tkinter import OptionMenu, Label, Button, Entry, StringVar
global e1,root,tkvar
gcamp_type = "Upgrade"

def change_dropdown(*args):
    global gcamp_type
    gcamp_type = tkvar.get()


graph_data = []
subj_line = ""
mape = 0
accuracy = 0
predictg = 0

def show_entry_fields():

    global graph_data, gcamp_type
    graph_data = [0.5,0.3]
    print(graph_data)

    global predictg
    global mape,accuracy
    mape = 5.4
    accuracy = 94.6
    root.destroy()

global cnt 
cnt = 0

def quit_func():
    global cnt
    cnt = -1
    root.destroy()

def main():
    global root
    global tkvar
    global e1
    global cnt
    global all_subj,all_words
    while True:
        cnt += 1
        all_subj = []
        all_words = []
        root = tk.Tk()
        root.title("Input")
        tkvar = StringVar(root)
        choices = { 'Upgrade','MGM','LOC_LCLP','SUPP','CrossSell'}
        tkvar.set('Upgrade')

        popupMenu = OptionMenu(root, tkvar, *choices)   
        popupMenu.config(width=10)
        popupMenu.grid(row = 0, column=3,padx=5)

        tkvar.trace('w', change_dropdown)

        text = Label(root,text="Subject Line",width='10')
        text.grid(row=0,column=0,pady=5,padx=5)
        e1 = Entry(root,width='70')
        e1.insert(0,subj_line)
        e1.grid(row=0,column=1,pady=5,padx=5,columnspan=2)
        b = Button(root, text='Run', command=show_entry_fields)
        b.grid(row=0,column=4,pady=5)
        b = Button(root, text='Quit', command=quit_func)
        b.grid(row=0,column=5,pady=5,padx=5)

        c_width = 700  # Define it's width
        c_height = 200 # Define it's height
        c = tk.Canvas(root, width=c_width, height=c_height, bg='white')
        c.grid(row=1,column=0,columnspan=6,pady=5)

        # The variables below size the bar graph
        y_stretch = 15  # The highest y = max_data_value * y_stretch
        y_gap = 20  # The gap between lower canvas edge and x axis
        x_stretch = 40 # Stretch x wide enough to fit the variables
        x_width = 20  # The width of the x-axis
        x_gap = 20  # The gap between left canvas edge and y axis

        # A quick for loop to calculate the rectangle
        hh = ['Brand', 'Travel', 'Benefit', 'Special', 'Greeting', 'Reward', 'Card', 'Money', 'Time', 'Location', 'Verb', 'Name', 'Adjective', 'Action', 'Relation', 'Question', 'Event', 'Amex', 'Business', 'Feel', 'Appreciate', 'Congrats', 'Frequency', 'Global', 'Local', 'Urgency', 'Inform', 'Meal', 'Member', 'Pay', 'Request', 'Secure', 'Multiple', 'Offer', 'Remind', 'Attention']

        a_dat = []
        cl = 0
        g_text = []
        for x in graph_data:
            cl += 1
            if x > 0:
                a_dat.append(x)
                g_text.append(hh[cl-1])

        cl = 0

        c.create_text(300,25,anchor=tk.SW,text="Position Score")
        for x, y in enumerate(a_dat):
            if y > 0:
                # Bottom left coordinate
                x0 = x * x_stretch + x * x_width + x_gap + 15
                # Top left coordinates
                y0 = c_height - (y * 10 * y_stretch + y_gap)
                # Bottom right coordinates
                x1 = x * x_stretch + x * x_width + x_width + x_gap + 15
                # Top right coordinates
                y1 = c_height - y_gap
                # Draw the bar
                c.create_rectangle(x0, y0, x1, y1, fill="red")
                # Put the y value above the bar
                c.create_text(x0 -10 , y0, anchor=tk.SW, text=str(round(y,4)))
                c.create_text(x0 -10 , y1+20, anchor=tk.SW, text=g_text[cl])
                cl += 1

        text = Label(root,text="Predicted Open Rate")
        text.grid(row=2,column=0,pady=5,padx=5)
        c = tk.Canvas(root, width=40, height=20, bg='white')
        c.grid(row=2,column=1,pady=5)
        c.create_text(20,11, text=str(round(predictg,2)) + "%")
        text = Label(root,text="Mape")
        text.grid(row=2,column=2,sticky='e',pady=5)
        c = tk.Canvas(root, width=40, height=20, bg='white')
        c.grid(row=2,column=3,pady=5)
        c.create_text(20,11, text=str(round(mape,2)) + "%")
        text = Label(root,text="Accuracy")
        text.grid(row=2,column=4,pady=5)
        c = tk.Canvas(root, width=40, height=20, bg='white')
        c.grid(row=2,column=5,padx=5,pady=5)
        c.create_text(20,11, text=str(accuracy) + "%")
        root.mainloop()


if __name__ == '__main__':
    main()
...