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

Недавно я пытался построить игру на Python без pygame (я хотел испытания), но столкнулся с проблемой. Я не могу использовать цикл if в основном цикле.

Это код, который у меня есть сейчас, и я был бы признателен, если бы кто-нибудь мог мне помочь!

Я пыталсяочистите холст, а затем добавьте еще поля, но опять цикл if не будет работать. Я также пробовал циклы while и for, но они тоже не работают.

import tkinter as tk
import time

dieplease= "dieplease"
play = False
accepted = ["admin1 LET ME IN"] #accepted names
count = len(accepted)
score = 0

windowEA= tk.Tk()

boxy = tk.Canvas(windowEA, width = 400, height = 300)
boxy.pack()     #canvas adjustments

label1 = tk.Label(windowEA, text="""You need Authorisation to get into this file so, please enter
your username and password to be allowed to play.""")
label1.config(font=('helvetica', 12))   #tkinter canvas config
boxy.create_window(200, 25, window=label1)

entry1 = tk.Entry (windowEA)    #creation of username entry box
boxy.create_window(200, 100, window=entry1)
entry2 = tk.Entry (windowEA)    #creation of password entry box
boxy.create_window(200, 120, window=entry2)
entry2.config(show="*")

x1 = entry1.get()
x2 = entry2.get()
namer = x1+" "+x2

def namecheck (): #checking if the name given fits with the allowed ones
    global play
    found = False
    x1 = entry1.get()
    x2 = entry2.get()
    namer = x1+" "+x2

    for d in range(count):
        if namer == accepted[d]:
            found = True
    if found == True:
        label1 = tk.Label(windowEA, text= "welcome to the game")
        boxy.create_window(200, 230, window=label1)
        output = "welcome to the game"
        play = True
    else:
        label1 = tk.Label(windowEA, text= "Sorry incorrect information")
        boxy.create_window(200, 230, window=label1)
        output = "Sorry incorrect information"

def quit():
    boxy.delete("all")

button1 = tk.Button(text="check", command=namecheck)
boxy.create_window(220, 180, window=button1)    #checking if info is good button
button2 = tk.Button(text="Login", command=quit)
boxy.create_window(180, 180, window=button2)    #login on button

if play == True:
    print("HI") #checking
    #this is where I want it to work
windowEA.mainloop()

1 Ответ

0 голосов
/ 10 октября 2019

Используйте метод .after в tkinter для планирования функции, которая будет вызываться периодически, скажем, каждые 100 мс.

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

import tkinter as tk

def update():
    #Code here to perform your if and any other code
    print("Updating")
    root.after(100,update)

root = tk.Tk()

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