Отображение метки после нажатия кнопки Tkinter - PullRequest
0 голосов
/ 12 декабря 2018

Я пытаюсь сделать так, чтобы ответ на мой волшебный симулятор 8 шаров в tkinter появился после нажатия кнопки вычисления.Если есть какой-то способ исправить это, я был бы очень благодарен.

def __init__(self, window):
    ''' Constructor '''
    self.window = window 
    self.window.protocol('WM_DELETE_WINDOW', self.safe_exit)
    self.width = 400
    self.input1 = StringVar()
    self.result = StringVar()

    ''' Creates the introduction label '''
    intro_label = tk.Label(window, text="Welcome to the Magic 8 Ball Simulator. Ask the Magic 8 Ball a question and you shall receive an answer: ")
    intro_label.pack()

    ''' Creates the canvas '''
    self.canvas = tk.Canvas(self.window, bg='white',
                    width=self.width, height=self.width)
    self.canvas.pack()

    ''' Image borrowed from giphy.com'''
    self.canvas.image = tk.PhotoImage(file='C:/Users/jakem/OneDrive/Desktop/8Ball.gif')
    self.canvas.create_image(200,200, image=self.canvas.image,)

    ''' Creates a Second Input Label '''
    Question_label = tk.Label(window, text="Please enter your question: ")
    Question_label.pack()

    '''Allows user to enter a question'''
    Question_entry = tk.Entry(window, textvariable=self.input1, width=50)
    Question_entry.pack()

    ''' Returns an answer to the asked question '''
    answer_button = tk.Button(self.window, text='Ask the Magic 8 Ball', command= self.answer)
    answer_button.pack()

    ''' Label which determines the fate of the user '''
    Ball_label = tk.Label(window, text = "The Magic 8 Ball has determined your fate: ")
    Ball_label.pack()

    ''' Displays the result from a list of available options '''
    Result_label = tk.Label(window, text = '', width=25)
    Result_label.pack()

    ''' Returns an answer to the asked question '''
    Repeat_button = tk.Button(self.window, text='Ask another query', command=self.answer())
    Repeat_button.pack()

    self.terminated = False

    if answer_button == onClick:
        Result_label.config(textvariable = self.result)

    tk.Button(root, text="Quit", command=root.destroy).pack()

def safe_exit(self):
    ''' Turn off the event loop before closing the GUI '''
    self.terminated = True
    self.window.destroy()

def answer(self):
    ''' Returns a randomly selected answer '''
    result = random.choice(answer_list)
    self.result.set(result)

def __init__(self,window):    
    Result_label.config(textvariable = self.result)


#def repeat(self):
    #Question_label.set('')
    #Ball_label.set('')

Ответы [ 2 ]

0 голосов
/ 13 декабря 2018

Я заметил несколько проблем с вашим кодом.Сначала вы определили этот метод дважды:

def __init__(self,window):

Затем вы забыли добавить префикс StringVar() к tk.StringVar():

self.input1 = StringVar()
self.result = StringVar()

Команда для этой кнопки не будет работать, потому чтовы передали результат self.answer(), а не self.answer:

Repeat_button = tk.Button(self.window, text='Ask another query', command=self.answer())

Вот моя упрощенная переделка вашей программы для решения вышеуказанных проблем и обеспечения ее работы в принципе, без изображения Magic 8 Ball:

import tkinter as tk
import random

CANVAS_WIDTH = 400

class Magic8Ball:

    def __init__(self, window):
        ''' Constructor '''

        self.input = tk.StringVar()
        self.result = tk.StringVar()
        self.memory = dict()
        self.terminated = False

        self.answer_list = ["Yes", "Maybe", "No"]  # I needed to put this somewhere

        # Create the introduction label
        tk.Label(window, text="Welcome to the Magic 8 Ball Simulator. Ask a question and you shall receive an answer:").pack()

        # Create the canvas
        self.canvas = tk.Canvas(window, width=CANVAS_WIDTH, height=CANVAS_WIDTH)
        self.canvas.pack()

        # Image borrowed from giphy.com
        # self.canvas_image = tk.PhotoImage(file='C:/Users/jakem/OneDrive/Desktop/8Ball.gif')
        # self.canvas.create_image(200, 200, image=self.canvas_image)

        # Create a Second Input Label
        question_label = tk.Label(window, text="Please enter your question:")
        question_label.pack()

        # Allow user to enter a question
        tk.Entry(window, textvariable=self.input, width=50).pack()

        # Return an answer to the asked question
        tk.Button(window, text='Ask the Magic 8 Ball', command=self.answer).pack()

        # Label which determines the fate of the user
        tk.Label(window, text="The Magic 8 Ball has determined your fate:").pack()

        # Display the result from a list of available options
        tk.Label(window, text='', width=25, textvariable=self.result).pack()

        tk.Button(window, text="Quit", command=root.destroy).pack()

    def answer(self):
        ''' Returns a randomly selected answer '''

        question = self.input.get()

        if question:  # don't answer if nothing's been asked
            if question in self.memory:
                result = self.memory[question]  # if a question is repeated,  be consistent
            else:
                result = random.choice(self.answer_list)
                self.memory[question] = result

            self.result.set(result)

root = tk.Tk()

app = Magic8Ball(root)

root.mainloop()

Не используйте строки в тройных кавычках в качестве механизма общего комментария.Может использоваться для строк документации , которые предоставляют конкретную информацию и расположены в определенных местах в вашем коде.В противном случае используйте стандартный символ комментария.

0 голосов
/ 12 декабря 2018

Вместо:

Result_label.config(textvariable = self.result)

Попробуйте:

Result_label.config(text = self.result.get())
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...