Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Помогите с дз(

Канокотик Ученик (98), на голосовании 4 недели назад
размести 4 кнопки в середине экрана. Пусть при создании кнопок случайная из них выбирается правильной, цель игрока - выбрать правильную. При нажатии на правильную появляется текст Ты угадал. При нажатии на неправильную - удаляются все неправильные и появляется текст Ты не угадал
Голосование за лучший ответ
oscrn Мастер (1807) 2 месяца назад
 import tkinter as tk 
import random

# Function to handle button click
def button_click(button_id):
global correct_button_id
if button_id == correct_button_id:
message_label.config(text='Ты угадал')
else:
message_label.config(text='Ты не угадал')
# Remove all incorrect buttons
for btn in buttons:
if btn['text'] != correct_button_id:
btn.destroy()

# Create the main window
root = tk.Tk()
root.title('Угадай кнопку')
root.geometry('300x300')

# Create a list of button IDs
button_ids = ['1', '2', '3', '4']

# Randomly select the correct button
correct_button_id = random.choice(button_ids)

# Create buttons and place them in the center
buttons = []
for button_id in button_ids:
btn = tk.Button(root, text=button_id, command=lambda id=button_id: button_click(id))
buttons.append(btn)

# Place buttons in a grid to center them
for i, btn in enumerate(buttons):
btn.grid(row=1, column=i)

# Label to display messages
message_label = tk.Label(root, text='Выберите кнопку')
message_label.grid(row=2, columnspan=4)

# Run the application
root.mainloop()
КанокотикУченик (98) 2 месяца назад
спасибо
Андрей Антонов Мудрец (10613) 2 месяца назад
import tkinter as tk
from tkinter import messagebox
import random

def create_buttons():
global correct_button
# Случайно выбираем правильную кнопку
correct_button = random.randint(0, 3)

for i in range(4):
button = tk.Button(root, text=f"Кнопка {i+1}", font=("Arial", 16), width=10, height=2)
button.grid(row=0, column=i, padx=10, pady=10)

# Привязываем обработчик нажатия к каждой кнопке
if i == correct_button:
button.config(command=lambda: on_correct_click())
else:
button.config(command=lambda b=button: on_incorrect_click(b))

buttons.append(button)

def on_correct_click():
messagebox.showinfo("Результат", "Ты угадал!")
root.quit() # Завершаем программу после правильного выбора

def on_incorrect_click(button):
# Удаляем все неправильные кнопки
for btn in buttons:
if btn != buttons[correct_button]:
btn.destroy()

messagebox.showinfo("Результат", "Ты не угадал")
root.quit() # Завершаем программу после неправильного выбора

# Создаем главное окно
root = tk.Tk ()
root.title("Угадай кнопку")
root.geometry("500x200")

# Центрируем окно на экране
root.update_idletasks()
width = root.winfo_width()
height = root.winfo_height()
x = (root.winfo_screenwidth() // 2) - (width // 2)
y = (root.winfo_screenheight() // 2) - (height // 2)
root.geometry(f"+{x}+{y}")

# Список для хранения кнопок
buttons = []

# Создаем кнопки
create_buttons()

# Запускаем главный цикл
root.mainloop()
Похожие вопросы