python управление потоком виджетов tkinter - PullRequest
0 голосов
/ 13 февраля 2020

Я пытался поработать над этим проектом некоторое время и почти закончил, но я не могу понять поток управления. когда я вызываю функцию main_menu (), она должна давать две кнопки, а если нажать одну, она меняет выбор на 1 или 2, исходя из того, что должна отображаться новая доска. Однако он никогда не перемещается в оператор if. В основном, как мне выполнить строку кода (выбор == 1), если я нажимаю кнопку быстрого доступа. Любая помощь будет оценена.

import tkinter as tk
import random
import re

root = tk.Tk()

def scramble_board():
    new_board = ''.join(str(item) for i in board for item in i)
    shuffle_board = ''.join(random.sample(new_board, len(new_board)))
    new_shuffle = list(shuffle_board)
    return(new_shuffle)

def getWords(counter):
    first_letter = board[0][counter]
    last_letter = board[3][counter]
    new_words = [word for word in words.split() if(word.startswith(first_letter) and word.endswith(last_letter))]
    if(len(new_words) == 0):
        return('')
    else:
        return(random.choice(new_words))

def choice1():
    global choice
    choice = 1
    #clear_screen()
    return choice

def choice2():
    global choice
    choice = 2
    #clear_screen()

def clear_screen():
    for i in root.winfo_children():
        i.destroy()

choice = 3    
HEIGHT = 600
WIDTH = 600
root.geometry("600x600")
var = tk.IntVar()

canvas = tk.Canvas(root)
canvas.pack()

def main_menu():
    clear_screen()
    easy_button = tk.Button(root, text = "Easy", command = lambda: choice1())
    easy_button.place(relx =.43, rely =.3, width = 85, height = 35)
    med_button = tk.Button(root, text = "Medium", command = lambda: choice2())
    med_button.place(relx = .43, rely = .6, width = 85, height = 35)
    #easy_button.wait_variable(var)
    #med_button.wait_variable(var)
    root.wait_variable(var)


#while(choice ==3):
main_menu()
    #easy_button.wait_variable(var)
    #med_button.wait_variable(var)
    #root.wait_variable(var)

#while(choice != 3):
if(choice==1):

    print('hello')
    len_of_word = 3
    board = [["a", "a", "a"], ["a", "a", "a"], ["a", "a", "a"]]
    complete = False
    file_3 = "word_list_4.txt"
    file = open(file_3)
    words = file.read()
    pre_word = ["a", "a", "a"]

    while(complete == False):
        count = 0
        for i in range(len_of_word):
            word = (list(random.choice(open(file_3).read().split())))
            for j in range(len_of_word):
                board[i][j] = word[j]
        for i in range(len_of_word):
            for j in range(len_of_word):
                pre_word[j] = board[j][i]
                word_check = ''.join(pre_word)
            if word_check in words:
                count = count + 1
                if(count ==3):
                    print(board)
                    complete = True
        shuffled = scramble_board()            
        shuffled

    clear_screen()
    #frame is colored bit inside of canvas, .place is used to set the frame relative to the window
    #if the window is stretched by the user so will the frame.
    frame_game_screen = tk.Frame(root, bg = 'gray')
    frame_game_screen.place(relx = .2, rely = .1, relwidth = .6, relheight = .6)

1 Ответ

0 голосов
/ 13 февраля 2020

Вот решение для вас:

Все, что вам нужно сделать, это сделать следующие два шага:

  • Поместить оператор if в функцию (например: if_func) где-то до choice1 и choice2, глобализировать boards и words. Вот так:
def if_func():
    global board, words

    if choice == 1:

        print('hello')
        len_of_word = 3
        board = [["a", "a", "a"], ["a", "a", "a"], ["a", "a", "a"]]
        complete = False
        file_3 = "word_list_4.txt"
        file = open(file_3)
        words = file.read()
        pre_word = ["a", "a", "a"]

        while complete == False:
            count = 0
            for i in range(len_of_word):
                word = (list(random.choice(open(file_3).read().split())))
                for j in range(len_of_word):
                    board[i][j] = word[j]
            for i in range(len_of_word):
                for j in range(len_of_word):
                    pre_word[j] = board[j][i]
                    word_check = ''.join(pre_word)
                if word_check in words:
                    count = count + 1
                    if count == 3:
                        print(board)
                        complete = True
            shuffled = scramble_board()
            shuffled

        clear_screen()

        # frame is colored a bit inside of canvas, .place is used to set the frame relative to the window
        # if the window is stretched by the user so will the frame.

        frame_game_screen = tk.Frame(root, bg='gray')
        frame_game_screen.place(relx=.2, rely=.1, relwidth=.6, relheight=.6)
  • Вызовите эту функцию (if_func) внутри ваших функций choice1 и choice2. Как это:
def choice1():
    global choice
    choice = 1
    # clear_screen()
    if_func()


def choice2():
    global choice
    choice = 2
    if_func()

Примечание: Помещение if в функцию позволит вам использовать ее столько раз, сколько вы захотите. Вне функции она будет выполняться только один раз при запуске программы, следовательно, это не будет иметь значения.

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