Уведомления

Группа в Telegram: @pythonsu

#1 Янв. 10, 2021 15:50:22

R_M
Зарегистрирован: 2021-01-10
Сообщения: 2
Репутация: +  0  -
Профиль   Отправить e-mail  

Помогите сделать своеобразные "крестики-нолики"

У меня есть код, он выводит поле 3х3, как сделать так, что бы при нажатии квадраты закрашивались причем поочередно, то есть раз нажал- закрасилось красным, второй раз- зеленым, третий раз опять красным

from tkinter import *
from functools import partial
from tkinter import messagebox

root=Tk()
root.resizable(0, 0)
root.geometry(“150x150”)


def zm(Event,x,y):
print(Event,x)


def change(event):
b = “#000000”
b = “#000000”
#===================================================
y=0
krd=3
kst=3
for rd in range(krd):
for st in range(kst):
b=Button(root,bg=“#669999”)
b.place(x=st*50,y=y,width=50,heigh=50)
xx=b.place_info()
yy=y
b.bind('<Button-1>', partial(zm,xx,yy))
b.bind('<Button-1>', change)
y+=50


root.mainloop()

p.s. обьясните пожалуйста почему def change(event): окрашивает только нижнюю правую кнопку причем при нажатии на любую из девяти кнопок

Офлайн

#2 Янв. 10, 2021 17:11:05

xam1816
Зарегистрирован: 2020-05-11
Сообщения: 1309
Репутация: +  113  -
Профиль   Отправить e-mail  

Помогите сделать своеобразные "крестики-нолики"

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

Офлайн

#3 Янв. 10, 2021 20:53:59

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

Помогите сделать своеобразные "крестики-нолики"

1 программа в 2х файлах

 #! /usr/bin/env python
#  -*- coding: utf-8 -*-
import sys
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk
try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True
import unknown_support
def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = tk.Tk()
    top = Toplevel1 (root)
    unknown_support.init(root, top)
    root.mainloop()
w = None
def create_Toplevel1(rt, *args, **kwargs):
    '''Starting point when module is imported by another module.
       Correct form of call: 'create_Toplevel1(root, *args, **kwargs)' .'''
    global w, w_win, root
    #rt = root
    root = rt
    w = tk.Toplevel (root)
    top = Toplevel1 (w)
    unknown_support.init(w, top, *args, **kwargs)
    return (w, top)
def destroy_Toplevel1():
    global w
    w.destroy()
    w = None
class Toplevel1:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        
        self.foreground=["#ff0000", "#7af500"]
        self.foreground_state = 0
        
        self.tabl = {1: None, 2: None, 3: None,
                     4: None, 5: None, 6: None,
                     7: None, 8: None, 9: None}
        top.geometry("261x202+420+150")
        top.minsize(116, 1)
        top.maxsize(1440, 878)
        top.resizable(1,  1)
        top.title("New Toplevel")
        top.configure(background="#d9d9d9")
        self.Labelframe1 = tk.LabelFrame(top)
        self.Labelframe1.place(relx=0.038, rely=0.045, relheight=0.738
                , relwidth=0.931)
        self.Labelframe1.configure(relief='groove')
        self.lbl()
        self.Labelframe1.configure(text='''ход игрока этого цвета''')
        self.Labelframe1.configure(background="#d9d9d9")
        self.Button1 = tk.Button(self.Labelframe1)
        self.Button1.place(relx=0.041, rely=0.195, height=24, width=47
                , bordermode='ignore')
        self.Button1.configure(activebackground="#ececec")
        self.Button1.configure(activeforeground="#000000")
        self.Button1.configure(background="#d9d9d9")
        self.Button1.configure(disabledforeground="#a3a3a3")
        self.Button1.configure(foreground="#000000")
        self.Button1.configure(highlightbackground="#d9d9d9")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(pady="0")
        self.Button1.bind('<Button-1>', self.n1)
        self.Button2 = tk.Button(self.Labelframe1)
        self.Button2.place(relx=0.329, rely=0.201, height=24, width=47
                , bordermode='ignore')
        self.Button2.configure(activebackground="#ececec")
        self.Button2.configure(activeforeground="#000000")
        self.Button2.configure(background="#d9d9d9")
        self.Button2.configure(disabledforeground="#a3a3a3")
        self.Button2.configure(foreground="#000000")
        self.Button2.configure(highlightbackground="#d9d9d9")
        self.Button2.configure(highlightcolor="black")
        self.Button2.configure(pady="0")
        self.Button2.bind('<Button-1>', self.n2)
        self.Button3 = tk.Button(self.Labelframe1)
        self.Button3.place(relx=0.576, rely=0.201, height=24, width=47
                , bordermode='ignore')
        self.Button3.configure(activebackground="#ececec")
        self.Button3.configure(activeforeground="#000000")
        self.Button3.configure(background="#d9d9d9")
        self.Button3.configure(disabledforeground="#a3a3a3")
        self.Button3.configure(foreground="#000000")
        self.Button3.configure(highlightbackground="#d9d9d9")
        self.Button3.configure(highlightcolor="black")
        self.Button3.configure(pady="0")
        self.Button3.bind('<Button-1>', self.n3)
        self.Button4 = tk.Button(self.Labelframe1)
        self.Button4.place(relx=0.041, rely=0.403, height=24, width=47
                , bordermode='ignore')
        self.Button4.configure(activebackground="#ececec")
        self.Button4.configure(activeforeground="#000000")
        self.Button4.configure(background="#d9d9d9")
        self.Button4.configure(disabledforeground="#a3a3a3")
        self.Button4.configure(foreground="#000000")
        self.Button4.configure(highlightbackground="#d9d9d9")
        self.Button4.configure(highlightcolor="black")
        self.Button4.configure(pady="0")
        self.Button4.bind('<Button-1>', self.n4)
        self.Button5 = tk.Button(self.Labelframe1)
        self.Button5.place(relx=0.329, rely=0.403, height=24, width=47
                , bordermode='ignore')
        self.Button5.configure(activebackground="#ececec")
        self.Button5.configure(activeforeground="#000000")
        self.Button5.configure(background="#d9d9d9")
        self.Button5.configure(disabledforeground="#a3a3a3")
        self.Button5.configure(foreground="#000000")
        self.Button5.configure(highlightbackground="#d9d9d9")
        self.Button5.configure(highlightcolor="black")
        self.Button5.configure(pady="0")
        self.Button5.bind('<Button-1>', self.n5)
        self.Button6 = tk.Button(self.Labelframe1)
        self.Button6.place(relx=0.576, rely=0.403, height=24, width=47
                , bordermode='ignore')
        self.Button6.configure(activebackground="#ececec")
        self.Button6.configure(activeforeground="#000000")
        self.Button6.configure(background="#d9d9d9")
        self.Button6.configure(disabledforeground="#a3a3a3")
        self.Button6.configure(foreground="#000000")
        self.Button6.configure(highlightbackground="#d9d9d9")
        self.Button6.configure(highlightcolor="black")
        self.Button6.configure(pady="0")
        self.Button6.bind('<Button-1>', self.n6)
        self.Button7 = tk.Button(self.Labelframe1)
        self.Button7.place(relx=0.041, rely=0.651, height=24, width=47
                , bordermode='ignore')
        self.Button7.configure(activebackground="#ececec")
        self.Button7.configure(activeforeground="#000000")
        self.Button7.configure(background="#d9d9d9")
        self.Button7.configure(disabledforeground="#a3a3a3")
        self.Button7.configure(foreground="#000000")
        self.Button7.configure(highlightbackground="#d9d9d9")
        self.Button7.configure(highlightcolor="black")
        self.Button7.configure(pady="0")
        self.Button7.bind('<Button-1>', self.n7)
        self.Button8 = tk.Button(self.Labelframe1)
        self.Button8.place(relx=0.329, rely=0.671, height=24, width=47
                , bordermode='ignore')
        self.Button8.configure(activebackground="#ececec")
        self.Button8.configure(activeforeground="#000000")
        self.Button8.configure(background="#d9d9d9")
        self.Button8.configure(disabledforeground="#a3a3a3")
        self.Button8.configure(foreground="#000000")
        self.Button8.configure(highlightbackground="#d9d9d9")
        self.Button8.configure(highlightcolor="black")
        self.Button8.configure(pady="0")
        self.Button8.bind('<Button-1>', self.n8)
        self.Button9 = tk.Button(self.Labelframe1)
        self.Button9.place(relx=0.617, rely=0.671, height=24, width=47
                , bordermode='ignore')
        self.Button9.configure(activebackground="#ececec")
        self.Button9.configure(activeforeground="#000000")
        self.Button9.configure(background="#d9d9d9")
        self.Button9.configure(disabledforeground="#a3a3a3")
        self.Button9.configure(foreground="#000000")
        self.Button9.configure(highlightbackground="#d9d9d9")
        self.Button9.configure(highlightcolor="black")
        self.Button9.configure(pady="0")
        self.Button9.bind('<Button-1>', self.n9)
    
    def lbl(self):
        if self.foreground_state:
            self.Labelframe1.configure(foreground=self.foreground[1])
        else:
            self.Labelframe1.configure(foreground=self.foreground[0])
            
    def state(self):
        if self.foreground_state:
            self.foreground_state = 0
        else:
            self.foreground_state = 1
            
    def n(self, num , obj):
        if self.tabl[num] == None:
            self.tabl.update(
                {num: self.foreground[self.foreground_state]})
            obj.configure(
                background=self.foreground[self.foreground_state])
            self.state()
            self.lbl()
            self.result()
    def result(self):
        # здесь вам нужно высчитывать победителя 
        # этот метод просто эээ для того что бы было
        if not None in self.tabl.values():
            print(self.tabl)
            exit()
    def n1(self, eventorigin):
        self.n(1, self.Button1)
    def n2(self, eventorigin):
        self.n(2, self.Button2)
    def n3(self, eventorigin):
        self.n(3, self.Button3)
    def n4(self, eventorigin):
        self.n(4, self.Button4)
    def n5(self, eventorigin):
        self.n(5, self.Button5)
    def n6(self, eventorigin):
        self.n(6, self.Button6)
    def n7(self, eventorigin):
        self.n(7, self.Button7)
    def n8(self, eventorigin):
        self.n(8, self.Button8)
    def n9(self, eventorigin):
        self.n(9, self.Button9)
if __name__ == '__main__':
    vp_start_gui()

 #! /usr/bin/env python
#  -*- coding: utf-8 -*-
import sys
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk
try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True
def init(top, gui, *args, **kwargs):
    global w, top_level, root
    w = gui
    top_level = top
    root = top
def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None
if __name__ == '__main__':
    import unknown
    unknown.vp_start_gui()



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Отредактировано AD0DE412 (Янв. 10, 2021 20:57:22)

Офлайн

#4 Янв. 10, 2021 21:09:12

R_M
Зарегистрирован: 2021-01-10
Сообщения: 2
Репутация: +  0  -
Профиль   Отправить e-mail  

Помогите сделать своеобразные "крестики-нолики"

AD0DE412
1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
спасибо что объяснили

и за ответ огромное спасибо!!

Офлайн

#5 Янв. 11, 2021 05:39:02

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

Помогите сделать своеобразные "крестики-нолики"

не … это не все …

а теперь поробуйте заменить например
self.Button9.bind('<Button-1>', self.n9)
на
self.Button9.configure(command=lambda: self.n(9, self.Button9))

или лучше
self.Button9.bind('<Button-1>', lambda x: self.n(9, self.Button9))

зы первый файл предидущего моего поста называется unknown.py ну а второй unknown_support.py



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Отредактировано AD0DE412 (Янв. 11, 2021 06:39:23)

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version