Как исправить мою функцию, чтобы она работала в моем приложении Tkinter (Guessing Game) - PullRequest
0 голосов
/ 21 января 2019

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

Я пробовал несколько вещей, таких как использование словарей и получение ключа, но он не повторяется после нажатия кнопки.

Это код, который отлично работает:

while answers == True:
answers = ["Sayajin", "Namek", "Cell", "TournamentOfPower"]
for a in  range(4):

    s = input()
    if s in answers[0]:
        print("Richtig")
        answers.pop(0)

Это код, который не работает:

def check(event):
answers = ["Sayajin", "Namek", "Cell", "TournamentOfPower"]
for a in range(4):

    s = entrysaga.get()
    if s in answers[0]:
        print("Richtig")
        answers.pop(0)

Полный код:

from tkinter import *
import tkinter.messagebox
import time
import random

root = Tk()

#Hint Button
hint = Button(root, text= "Hint")
hint.bind("<Button-1>")
hint.place(x=50, y=20)

#How to Play Button + Info Message how to play

def Howtoplay():
    tkinter.messagebox.showinfo("How to play", "To start the game u have 
to press the button (Start)\n--------------------------------------------- 
----------------\n"
                                           ""
                                           "Then the Picture will switch 
and its going to show u a Character and u have to guess from which Dragon 
Ball Saga he is.\n-------------------------------------------------------- 
-----\n"
                                           "Just type it in the Entry and 
press Check after that if u were right the next picture shows up")

info = Button(root, text="How to Play", command=Howtoplay)
info.bind("<Button-1>")
info.place(x=150, y=20)

#textwidget
textwidget = Label(root, text="Entry the DragonBall Saga:")

#entry widget
entrysaga = Entry(root)

#Pictures for guessing the Saga
Sayajin = PhotoImage(file="sayajinsaga.png")
Namek = PhotoImage(file="NamekSaga.png")
Cell = PhotoImage(file="CellSaga.png")
Buu = PhotoImage(file="BuuSaga.png")
TournamentOfPower = PhotoImage(file="TournamentOfPowersaga.png")

#Start function
def start():
    labelSagas.config(image=Sayajin)


#define check for pictures
def check(event):
    answers = ["Sayajin", "Namek", "Cell", "TournamentOfPower"]
    for a in range(4):

        s = entrysaga.get()
        if s in answers[0]:
            print("Richtig")
            answers.pop(0)

#button check
buttonsaga = Button(root, text="Check")
buttonsaga.bind("<Button-1>", check)

textwidget.place(x=300, y=170)
entrysaga.place(x=300, y= 200)
buttonsaga.place(x=440, y=195)

#Start Button
start = Button(root, text="Start", command=start)
start.bind("<Button-1")
start.place(x=400, y=20)

# Label with start picture,
startpic = PhotoImage(file="dbzsagas.png")
labelSagas = Label(root, image=startpic)
labelSagas.place(x=25, y=80)



#size of window
root.geometry("500x280")

#window title
root.title("Dragon Ball Saga´s guessing game")

#start of the window
root.mainloop()

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

1 Ответ

0 голосов
/ 21 января 2019

Я переместил виджеты, которые должны появиться при нажатии кнопки Start.Все они находятся в функции def start():, так как в противном случае они не отображались бы.

Поскольку entrysaga вызывался из другой функции, он не смог найти введенное значение, поскольку переменная не является глобальной переменной.Использование global entrysaga означает, что он вызывается и может вызываться из любого места в скрипте.

Вот как это выглядит:

from tkinter import *
import tkinter.messagebox
import time
import random

root = Tk()

#Hint Button
hint = Button(root, text= "Hint")
hint.bind("<Button-1>")
hint.place(x=50, y=20)

#How to Play Button + Info Message how to play

def Howtoplay():
    tkinter.messagebox.showinfo("How to play", "To start the game u have to press the button (Start)\n--------------------------------------------- ----------------\n"
                                           ""
                                           "Then the Picture will switch and its going to show u a Character and u have to guess from which Dragon Ball Saga he is.\n-------------------------------------------------------- -----\n"
                                           "Just type it in the Entry and press Check after that if u were right the next picture shows up")

info = Button(root, text="How to Play", command=Howtoplay)
info.bind("<Button-1>")
info.place(x=150, y=20)

#Pictures for guessing the Saga
Sayajin = PhotoImage(file="sayajinsaga.png")
Namek = PhotoImage(file="NamekSaga.png")
Cell = PhotoImage(file="CellSaga.png")
Buu = PhotoImage(file="BuuSaga.png")
TournamentOfPower = PhotoImage(file="TournamentOfPowersaga.png")

#Start function
def start():
    labelSagas.config(image=Sayajin)
    global entrysaga
    entrysaga = tkinter.Entry(root)
    entrysaga.place(x=300, y= 200)
    buttonsaga = Button(root, text="Check")
    buttonsaga.bind("<Button-1>", check)
    buttonsaga.place(x=440, y=195)
    textwidget = Label(root, text="Entry the DragonBall Saga:")
    textwidget.place(x=300, y=170)
#define check for pictures
def check(event):
    answers = ["Sayajin", "Namek", "Cell", "TournamentOfPower"]
    for a in range(4):

        s = entrysaga.get()
        if s in answers[0]:
            print("Richtig")
            answers.pop(0)

#Start Button
start = Button(root, text="Start", command=start)
start.bind("<Button-1")
start.place(x=400, y=20)

# Label with start picture,
startpic = PhotoImage(file="dbzsagas.png")
labelSagas = Label(root, image=startpic)
labelSagas.place(x=25, y=80)

#size of window
root.geometry("500x280")

#window title
root.title("Dragon Ball Saga´s guessing game")

#start of the window
root.mainloop()

Надеюсь, это поможет!:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...